(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,(function(r){var n=e[i][1][r];return o(n||r)}),p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;iarr.length)len=arr.length;for(var i=0,arr2=new Array(len);icode){return false}pos+=set[i+1];if(pos>=code){return true}}}function isIdentifierStart(code,astral){if(code<65){return code===36}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)}function isIdentifierChar(code,astral){if(code<48){return code===36}if(code<58){return true}if(code<65){return false}if(code<91){return true}if(code<97){return code===95}if(code<123){return true}if(code<=65535){return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))}if(astral===false){return false}return isInAstralSet(code,astralIdentifierStartCodes)||isInAstralSet(code,astralIdentifierCodes)}var TokenType=function TokenType(label,conf){if(conf===void 0)conf={};this.label=label;this.keyword=conf.keyword;this.beforeExpr=!!conf.beforeExpr;this.startsExpr=!!conf.startsExpr;this.isLoop=!!conf.isLoop;this.isAssign=!!conf.isAssign;this.prefix=!!conf.prefix;this.postfix=!!conf.postfix;this.binop=conf.binop||null;this.updateContext=null};function binop(name,prec){return new TokenType(name,{beforeExpr:true,binop:prec})}var beforeExpr={beforeExpr:true},startsExpr={startsExpr:true};var keywords={};function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywords[name]=new TokenType(name,options)}var types$1={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",startsExpr),privateId:new TokenType("privateId",startsExpr),eof:new TokenType("eof"),bracketL:new TokenType("[",{beforeExpr:true,startsExpr:true}),bracketR:new TokenType("]"),braceL:new TokenType("{",{beforeExpr:true,startsExpr:true}),braceR:new TokenType("}"),parenL:new TokenType("(",{beforeExpr:true,startsExpr:true}),parenR:new TokenType(")"),comma:new TokenType(",",beforeExpr),semi:new TokenType(";",beforeExpr),colon:new TokenType(":",beforeExpr),dot:new TokenType("."),question:new TokenType("?",beforeExpr),questionDot:new TokenType("?."),arrow:new TokenType("=>",beforeExpr),template:new TokenType("template"),invalidTemplate:new TokenType("invalidTemplate"),ellipsis:new TokenType("...",beforeExpr),backQuote:new TokenType("`",startsExpr),dollarBraceL:new TokenType("${",{beforeExpr:true,startsExpr:true}),eq:new TokenType("=",{beforeExpr:true,isAssign:true}),assign:new TokenType("_=",{beforeExpr:true,isAssign:true}),incDec:new TokenType("++/--",{prefix:true,postfix:true,startsExpr:true}),prefix:new TokenType("!/~",{beforeExpr:true,prefix:true,startsExpr:true}),logicalOR:binop("||",1),logicalAND:binop("&&",2),bitwiseOR:binop("|",3),bitwiseXOR:binop("^",4),bitwiseAND:binop("&",5),equality:binop("==/!=/===/!==",6),relational:binop("/<=/>=",7),bitShift:binop("<>/>>>",8),plusMin:new TokenType("+/-",{beforeExpr:true,binop:9,prefix:true,startsExpr:true}),modulo:binop("%",10),star:binop("*",10),slash:binop("/",10),starstar:new TokenType("**",{beforeExpr:true}),coalesce:binop("??",1),_break:kw("break"),_case:kw("case",beforeExpr),_catch:kw("catch"),_continue:kw("continue"),_debugger:kw("debugger"),_default:kw("default",beforeExpr),_do:kw("do",{isLoop:true,beforeExpr:true}),_else:kw("else",beforeExpr),_finally:kw("finally"),_for:kw("for",{isLoop:true}),_function:kw("function",startsExpr),_if:kw("if"),_return:kw("return",beforeExpr),_switch:kw("switch"),_throw:kw("throw",beforeExpr),_try:kw("try"),_var:kw("var"),_const:kw("const"),_while:kw("while",{isLoop:true}),_with:kw("with"),_new:kw("new",{beforeExpr:true,startsExpr:true}),_this:kw("this",startsExpr),_super:kw("super",startsExpr),_class:kw("class",startsExpr),_extends:kw("extends",beforeExpr),_export:kw("export"),_import:kw("import",startsExpr),_null:kw("null",startsExpr),_true:kw("true",startsExpr),_false:kw("false",startsExpr),_in:kw("in",{beforeExpr:true,binop:7}),_instanceof:kw("instanceof",{beforeExpr:true,binop:7}),_typeof:kw("typeof",{beforeExpr:true,prefix:true,startsExpr:true}),_void:kw("void",{beforeExpr:true,prefix:true,startsExpr:true}),_delete:kw("delete",{beforeExpr:true,prefix:true,startsExpr:true})};var lineBreak=/\r\n?|\n|\u2028|\u2029/;var lineBreakG=new RegExp(lineBreak.source,"g");function isNewLine(code){return code===10||code===13||code===8232||code===8233}function nextLineBreak(code,from,end){if(end===void 0)end=code.length;for(var i=from;i=2015){options.ecmaVersion-=2009}if(options.allowReserved==null){options.allowReserved=options.ecmaVersion<5}if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){return tokens.push(token)}}if(isArray(options.onComment)){options.onComment=pushComment(options,options.onComment)}return options}function pushComment(options,array){return function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation(this,startLoc,endLoc)}if(options.ranges){comment.range=[start,end]}array.push(comment)}}var SCOPE_TOP=1,SCOPE_FUNCTION=2,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128,SCOPE_CLASS_STATIC_BLOCK=256,SCOPE_VAR=SCOPE_TOP|SCOPE_FUNCTION|SCOPE_CLASS_STATIC_BLOCK;function functionFlags(async,generator){return SCOPE_FUNCTION|(async?SCOPE_ASYNC:0)|(generator?SCOPE_GENERATOR:0)}var BIND_NONE=0,BIND_VAR=1,BIND_LEXICAL=2,BIND_FUNCTION=3,BIND_SIMPLE_CATCH=4,BIND_OUTSIDE=5;var Parser=function Parser(options,input,startPos){this.options=options=getOptions(options);this.sourceFile=options.sourceFile;this.keywords=wordsRegexp(keywords$1[options.ecmaVersion>=6?6:options.sourceType==="module"?"5module":5]);var reserved="";if(options.allowReserved!==true){reserved=reservedWords[options.ecmaVersion>=6?6:options.ecmaVersion===5?5:3];if(options.sourceType==="module"){reserved+=" await"}}this.reservedWords=wordsRegexp(reserved);var reservedStrict=(reserved?reserved+" ":"")+reservedWords.strict;this.reservedWordsStrict=wordsRegexp(reservedStrict);this.reservedWordsStrictBind=wordsRegexp(reservedStrict+" "+reservedWords.strictBind);this.input=String(input);this.containsEsc=false;if(startPos){this.pos=startPos;this.lineStart=this.input.lastIndexOf("\n",startPos-1)+1;this.curLine=this.input.slice(0,this.lineStart).split(lineBreak).length}else{this.pos=this.lineStart=0;this.curLine=1}this.type=types$1.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=true;this.inModule=options.sourceType==="module";this.strict=this.inModule||this.strictDirective(this.pos);this.potentialArrowAt=-1;this.potentialArrowInForAwait=false;this.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports=Object.create(null);if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null;this.privateNameStack=[]};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},canAwait:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},allowNewDotTarget:{configurable:true},inClassStaticBlock:{configurable:true}};Parser.prototype.parse=function parse(){var node=this.options.program||this.startNode();this.nextToken();return this.parseTopLevel(node)};prototypeAccessors.inFunction.get=function(){return(this.currentVarScope().flags&SCOPE_FUNCTION)>0};prototypeAccessors.inGenerator.get=function(){return(this.currentVarScope().flags&SCOPE_GENERATOR)>0&&!this.currentVarScope().inClassFieldInit};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0&&!this.currentVarScope().inClassFieldInit};prototypeAccessors.canAwait.get=function(){for(var i=this.scopeStack.length-1;i>=0;i--){var scope=this.scopeStack[i];if(scope.inClassFieldInit||scope.flags&SCOPE_CLASS_STATIC_BLOCK){return false}if(scope.flags&SCOPE_FUNCTION){return(scope.flags&SCOPE_ASYNC)>0}}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction};prototypeAccessors.allowSuper.get=function(){var ref=this.currentThisScope();var flags=ref.flags;var inClassFieldInit=ref.inClassFieldInit;return(flags&SCOPE_SUPER)>0||inClassFieldInit||this.options.allowSuperOutsideMethod};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};prototypeAccessors.allowNewDotTarget.get=function(){var ref=this.currentThisScope();var flags=ref.flags;var inClassFieldInit=ref.inClassFieldInit;return(flags&(SCOPE_FUNCTION|SCOPE_CLASS_STATIC_BLOCK))>0||inClassFieldInit};prototypeAccessors.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&SCOPE_CLASS_STATIC_BLOCK)>0};Parser.extend=function extend(){var plugins=[],len=arguments.length;while(len--)plugins[len]=arguments[len];var cls=this;for(var i=0;i=,?^&]/.test(next)||next==="!"&&this.input.charAt(end+1)==="=")}start+=match[0].length;skipWhiteSpace.lastIndex=start;start+=skipWhiteSpace.exec(this.input)[0].length;if(this.input[start]===";"){start++}}};pp$9.eat=function(type){if(this.type===type){this.next();return true}else{return false}};pp$9.isContextual=function(name){return this.type===types$1.name&&this.value===name&&!this.containsEsc};pp$9.eatContextual=function(name){if(!this.isContextual(name)){return false}this.next();return true};pp$9.expectContextual=function(name){if(!this.eatContextual(name)){this.unexpected()}};pp$9.canInsertSemicolon=function(){return this.type===types$1.eof||this.type===types$1.braceR||lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$9.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};pp$9.semicolon=function(){if(!this.eat(types$1.semi)&&!this.insertSemicolon()){this.unexpected()}};pp$9.afterTrailingComma=function(tokType,notNext){if(this.type===tokType){if(this.options.onTrailingComma){this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc)}if(!notNext){this.next()}return true}};pp$9.expect=function(type){this.eat(type)||this.unexpected()};pp$9.unexpected=function(pos){this.raise(pos!=null?pos:this.start,"Unexpected token")};function DestructuringErrors(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1}pp$9.checkPatternErrors=function(refDestructuringErrors,isAssign){if(!refDestructuringErrors){return}if(refDestructuringErrors.trailingComma>-1){this.raiseRecoverable(refDestructuringErrors.trailingComma,"Comma is not permitted after the rest element")}var parens=isAssign?refDestructuringErrors.parenthesizedAssign:refDestructuringErrors.parenthesizedBind;if(parens>-1){this.raiseRecoverable(parens,"Parenthesized pattern")}};pp$9.checkExpressionErrors=function(refDestructuringErrors,andThrow){if(!refDestructuringErrors){return false}var shorthandAssign=refDestructuringErrors.shorthandAssign;var doubleProto=refDestructuringErrors.doubleProto;if(!andThrow){return shorthandAssign>=0||doubleProto>=0}if(shorthandAssign>=0){this.raise(shorthandAssign,"Shorthand property assignments are valid only in destructuring patterns")}if(doubleProto>=0){this.raiseRecoverable(doubleProto,"Redefinition of __proto__ property")}};pp$9.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos55295&&nextCh<56320){return true}if(context){return false}if(nextCh===123){return true}if(isIdentifierStart(nextCh,true)){var pos=next+1;while(isIdentifierChar(nextCh=this.input.charCodeAt(pos),true)){++pos}if(nextCh===92||nextCh>55295&&nextCh<56320){return true}var ident=this.input.slice(next,pos);if(!keywordRelationalOperator.test(ident)){return true}}return false};pp$8.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual("async")){return false}skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,after;return!lineBreak.test(this.input.slice(this.pos,next))&&this.input.slice(next,next+8)==="function"&&(next+8===this.input.length||!(isIdentifierChar(after=this.input.charCodeAt(next+8))||after>55295&&after<56320))};pp$8.parseStatement=function(context,topLevel,exports){var starttype=this.type,node=this.startNode(),kind;if(this.isLet(context)){starttype=types$1._var;kind="let"}switch(starttype){case types$1._break:case types$1._continue:return this.parseBreakContinueStatement(node,starttype.keyword);case types$1._debugger:return this.parseDebuggerStatement(node);case types$1._do:return this.parseDoStatement(node);case types$1._for:return this.parseForStatement(node);case types$1._function:if(context&&(this.strict||context!=="if"&&context!=="label")&&this.options.ecmaVersion>=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types$1._class:if(context){this.unexpected()}return this.parseClass(node,true);case types$1._if:return this.parseIfStatement(node);case types$1._return:return this.parseReturnStatement(node);case types$1._switch:return this.parseSwitchStatement(node);case types$1._throw:return this.parseThrowStatement(node);case types$1._try:return this.parseTryStatement(node);case types$1._const:case types$1._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types$1._while:return this.parseWhileStatement(node);case types$1._with:return this.parseWithStatement(node);case types$1.braceL:return this.parseBlock(true,node);case types$1.semi:return this.parseEmptyStatement(node);case types$1._export:case types$1._import:if(this.options.ecmaVersion>10&&starttype===types$1._import){skipWhiteSpace.lastIndex=this.pos;var skip=skipWhiteSpace.exec(this.input);var next=this.pos+skip[0].length,nextCh=this.input.charCodeAt(next);if(nextCh===40||nextCh===46){return this.parseExpressionStatement(node,this.parseExpression())}}if(!this.options.allowImportExportEverywhere){if(!topLevel){this.raise(this.start,"'import' and 'export' may only appear at the top level")}if(!this.inModule){this.raise(this.start,"'import' and 'export' may appear only with 'sourceType: module'")}}return starttype===types$1._import?this.parseImport(node):this.parseExport(node,exports);default:if(this.isAsyncFunction()){if(context){this.unexpected()}this.next();return this.parseFunctionStatement(node,true,!context)}var maybeName=this.value,expr=this.parseExpression();if(starttype===types$1.name&&expr.type==="Identifier"&&this.eat(types$1.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$8.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types$1.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types$1.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types$1.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$8.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types$1.parenL);if(this.type===types$1.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types$1._var||this.type===types$1._const||isLet){var init$1=this.startNode(),kind=isLet?"let":this.value;this.next();this.parseVar(init$1,true,kind);this.finishNode(init$1,"VariableDeclaration");if((this.type===types$1._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types$1._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}return this.parseForIn(node,init$1)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init$1)}var startsWithLet=this.isContextual("let"),isForOf=false;var refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(awaitAt>-1?"await":true,refDestructuringErrors);if(this.type===types$1._in||(isForOf=this.options.ecmaVersion>=6&&this.isContextual("of"))){if(this.options.ecmaVersion>=9){if(this.type===types$1._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}if(startsWithLet&&isForOf){this.raise(init.start,"The left-hand side of a for-of loop may not start with 'let'.")}this.toAssignable(init,false,refDestructuringErrors);this.checkLValPattern(init);return this.parseForIn(node,init)}else{this.checkExpressionErrors(refDestructuringErrors,true)}if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,init)};pp$8.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$8.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types$1._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$8.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types$1.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$8.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types$1.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types$1.braceR;){if(this.type===types$1._case||this.type===types$1._default){var isCase=this.type===types$1._case;if(cur){this.finishNode(cur,"SwitchCase")}node.cases.push(cur=this.startNode());cur.consequent=[];this.next();if(isCase){cur.test=this.parseExpression()}else{if(sawDefault){this.raiseRecoverable(this.lastTokStart,"Multiple default clauses")}sawDefault=true;cur.test=null}this.expect(types$1.colon)}else{if(!cur){this.unexpected()}cur.consequent.push(this.parseStatement(null))}}this.exitScope();if(cur){this.finishNode(cur,"SwitchCase")}this.next();this.labels.pop();return this.finishNode(node,"SwitchStatement")};pp$8.parseThrowStatement=function(node){this.next();if(lineBreak.test(this.input.slice(this.lastTokEnd,this.start))){this.raise(this.lastTokEnd,"Illegal newline after throw")}node.argument=this.parseExpression();this.semicolon();return this.finishNode(node,"ThrowStatement")};var empty$1=[];pp$8.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types$1._catch){var clause=this.startNode();this.next();if(this.eat(types$1.parenL)){clause.param=this.parseBindingAtom();var simple=clause.param.type==="Identifier";this.enterScope(simple?SCOPE_SIMPLE_CATCH:0);this.checkLValPattern(clause.param,simple?BIND_SIMPLE_CATCH:BIND_LEXICAL);this.expect(types$1.parenR)}else{if(this.options.ecmaVersion<10){this.unexpected()}clause.param=null;this.enterScope(0)}clause.body=this.parseBlock(false);this.exitScope();node.handler=this.finishNode(clause,"CatchClause")}node.finalizer=this.eat(types$1._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$8.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$8.parseWhileStatement=function(node){this.next();node.test=this.parseParenExpression();this.labels.push(loopLabel);node.body=this.parseStatement("while");this.labels.pop();return this.finishNode(node,"WhileStatement")};pp$8.parseWithStatement=function(node){if(this.strict){this.raise(this.start,"'with' in strict mode")}this.next();node.object=this.parseParenExpression();node.body=this.parseStatement("with");return this.finishNode(node,"WithStatement")};pp$8.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$8.parseLabeledStatement=function(node,maybeName,expr,context){for(var i$1=0,list=this.labels;i$1=0;i--){var label$1=this.labels[i];if(label$1.statementStart===node.start){label$1.statementStart=this.start;label$1.kind=kind}else{break}}this.labels.push({name:maybeName,kind:kind,statementStart:this.start});node.body=this.parseStatement(context?context.indexOf("label")===-1?context+"label":context:"label");this.labels.pop();node.label=expr;return this.finishNode(node,"LabeledStatement")};pp$8.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$8.parseBlock=function(createNewLexicalScope,node,exitStrict){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types$1.braceL);if(createNewLexicalScope){this.enterScope(0)}while(this.type!==types$1.braceR){var stmt=this.parseStatement(null);node.body.push(stmt)}if(exitStrict){this.strict=false}this.next();if(createNewLexicalScope){this.exitScope()}return this.finishNode(node,"BlockStatement")};pp$8.parseFor=function(node,init){node.init=init;this.expect(types$1.semi);node.test=this.type===types$1.semi?null:this.parseExpression();this.expect(types$1.semi);node.update=this.type===types$1.parenR?null:this.parseExpression();this.expect(types$1.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$8.parseForIn=function(node,init){var isForIn=this.type===types$1._in;this.next();if(init.type==="VariableDeclaration"&&init.declarations[0].init!=null&&(!isForIn||this.options.ecmaVersion<8||this.strict||init.kind!=="var"||init.declarations[0].id.type!=="Identifier")){this.raise(init.start,(isForIn?"for-in":"for-of")+" loop variable declaration may not have an initializer")}node.left=init;node.right=isForIn?this.parseExpression():this.parseMaybeAssign();this.expect(types$1.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$8.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types$1.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types$1._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types$1._in||this.isContextual("of")))){this.raise(this.lastTokEnd,"Complex binding patterns require an initialization value")}else{decl.init=null}node.declarations.push(this.finishNode(decl,"VariableDeclarator"));if(!this.eat(types$1.comma)){break}}return node};pp$8.parseVarId=function(decl,kind){decl.id=this.parseBindingAtom();this.checkLValPattern(decl.id,kind==="var"?BIND_VAR:BIND_LEXICAL,false)};var FUNC_STATEMENT=1,FUNC_HANGING_STATEMENT=2,FUNC_NULLABLE_ID=4;pp$8.parseFunction=function(node,statement,allowExpressionBody,isAsync,forInit){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types$1.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types$1.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types$1.name?null:this.parseIdent();if(node.id&&!(statement&FUNC_HANGING_STATEMENT)){this.checkLValSimple(node.id,this.strict||node.generator||node.async?this.treatFunctionsAsVar?BIND_VAR:BIND_LEXICAL:BIND_FUNCTION)}}var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(node.async,node.generator));if(!(statement&FUNC_STATEMENT)){node.id=this.type===types$1.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false,forInit);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$8.parseFunctionParams=function(node){this.expect(types$1.parenL);node.params=this.parseBindingList(types$1.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$8.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var privateNameMap=this.enterClassBody();var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types$1.braceL);while(this.type!==types$1.braceR){var element=this.parseClassElement(node.superClass!==null);if(element){classBody.body.push(element);if(element.type==="MethodDefinition"&&element.kind==="constructor"){if(hadConstructor){this.raise(element.start,"Duplicate constructor in the same class")}hadConstructor=true}else if(element.key&&element.key.type==="PrivateIdentifier"&&isPrivateNameConflicted(privateNameMap,element)){this.raiseRecoverable(element.key.start,"Identifier '#"+element.key.name+"' has already been declared")}}}this.strict=oldStrict;this.next();node.body=this.finishNode(classBody,"ClassBody");this.exitClassBody();return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$8.parseClassElement=function(constructorAllowsSuper){if(this.eat(types$1.semi)){return null}var ecmaVersion=this.options.ecmaVersion;var node=this.startNode();var keyName="";var isGenerator=false;var isAsync=false;var kind="method";var isStatic=false;if(this.eatContextual("static")){if(ecmaVersion>=13&&this.eat(types$1.braceL)){this.parseClassStaticBlock(node);return node}if(this.isClassElementNameStart()||this.type===types$1.star){isStatic=true}else{keyName="static"}}node.static=isStatic;if(!keyName&&ecmaVersion>=8&&this.eatContextual("async")){if((this.isClassElementNameStart()||this.type===types$1.star)&&!this.canInsertSemicolon()){isAsync=true}else{keyName="async"}}if(!keyName&&(ecmaVersion>=9||!isAsync)&&this.eat(types$1.star)){isGenerator=true}if(!keyName&&!isAsync&&!isGenerator){var lastValue=this.value;if(this.eatContextual("get")||this.eatContextual("set")){if(this.isClassElementNameStart()){kind=lastValue}else{keyName=lastValue}}}if(keyName){node.computed=false;node.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc);node.key.name=keyName;this.finishNode(node.key,"Identifier")}else{this.parseClassElementName(node)}if(ecmaVersion<13||this.type===types$1.parenL||kind!=="method"||isGenerator||isAsync){var isConstructor=!node.static&&checkKeyName(node,"constructor");var allowsDirectSuper=isConstructor&&constructorAllowsSuper;if(isConstructor&&kind!=="method"){this.raise(node.key.start,"Constructor can't have get/set modifier")}node.kind=isConstructor?"constructor":kind;this.parseClassMethod(node,isGenerator,isAsync,allowsDirectSuper)}else{this.parseClassField(node)}return node};pp$8.isClassElementNameStart=function(){return this.type===types$1.name||this.type===types$1.privateId||this.type===types$1.num||this.type===types$1.string||this.type===types$1.bracketL||this.type.keyword};pp$8.parseClassElementName=function(element){if(this.type===types$1.privateId){if(this.value==="constructor"){this.raise(this.start,"Classes can't have an element named '#constructor'")}element.computed=false;element.key=this.parsePrivateIdent()}else{this.parsePropertyName(element)}};pp$8.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){var key=method.key;if(method.kind==="constructor"){if(isGenerator){this.raise(key.start,"Constructor can't be a generator")}if(isAsync){this.raise(key.start,"Constructor can't be an async method")}}else if(method.static&&checkKeyName(method,"prototype")){this.raise(key.start,"Classes may not have a static property named prototype")}var value=method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&value.params.length!==0){this.raiseRecoverable(value.start,"getter should have no params")}if(method.kind==="set"&&value.params.length!==1){this.raiseRecoverable(value.start,"setter should have exactly one param")}if(method.kind==="set"&&value.params[0].type==="RestElement"){this.raiseRecoverable(value.params[0].start,"Setter cannot use rest params")}return this.finishNode(method,"MethodDefinition")};pp$8.parseClassField=function(field){if(checkKeyName(field,"constructor")){this.raise(field.key.start,"Classes can't have a field named 'constructor'")}else if(field.static&&checkKeyName(field,"prototype")){this.raise(field.key.start,"Classes can't have a static field named 'prototype'")}if(this.eat(types$1.eq)){var scope=this.currentThisScope();var inClassFieldInit=scope.inClassFieldInit;scope.inClassFieldInit=true;field.value=this.parseMaybeAssign();scope.inClassFieldInit=inClassFieldInit}else{field.value=null}this.semicolon();return this.finishNode(field,"PropertyDefinition")};pp$8.parseClassStaticBlock=function(node){node.body=[];var oldLabels=this.labels;this.labels=[];this.enterScope(SCOPE_CLASS_STATIC_BLOCK|SCOPE_SUPER);while(this.type!==types$1.braceR){var stmt=this.parseStatement(null);node.body.push(stmt)}this.next();this.exitScope();this.labels=oldLabels;return this.finishNode(node,"StaticBlock")};pp$8.parseClassId=function(node,isStatement){if(this.type===types$1.name){node.id=this.parseIdent();if(isStatement){this.checkLValSimple(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$8.parseClassSuper=function(node){node.superClass=this.eat(types$1._extends)?this.parseExprSubscripts(false):null};pp$8.enterClassBody=function(){var element={declared:Object.create(null),used:[]};this.privateNameStack.push(element);return element.declared};pp$8.exitClassBody=function(){var ref=this.privateNameStack.pop();var declared=ref.declared;var used=ref.used;var len=this.privateNameStack.length;var parent=len===0?null:this.privateNameStack[len-1];for(var i=0;i=11){if(this.eatContextual("as")){node.exported=this.parseModuleExportName();this.checkExport(exports,node.exported.name,this.lastTokStart)}else{node.exported=null}}this.expectContextual("from");if(this.type!==types$1.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types$1._default)){this.checkExport(exports,"default",this.lastTokStart);var isAsync;if(this.type===types$1._function||(isAsync=this.isAsyncFunction())){var fNode=this.startNode();this.next();if(isAsync){this.next()}node.declaration=this.parseFunction(fNode,FUNC_STATEMENT|FUNC_NULLABLE_ID,false,isAsync)}else if(this.type===types$1._class){var cNode=this.startNode();node.declaration=this.parseClass(cNode,"nullableID")}else{node.declaration=this.parseMaybeAssign();this.semicolon()}return this.finishNode(node,"ExportDefaultDeclaration")}if(this.shouldParseExportStatement()){node.declaration=this.parseStatement(null);if(node.declaration.type==="VariableDeclaration"){this.checkVariableExport(exports,node.declaration.declarations)}else{this.checkExport(exports,node.declaration.id.name,node.declaration.id.start)}node.specifiers=[];node.source=null}else{node.declaration=null;node.specifiers=this.parseExportSpecifiers(exports);if(this.eatContextual("from")){if(this.type!==types$1.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;i=13&&this.type===types$1.string){var stringLiteral=this.parseLiteral(this.value);if(loneSurrogate.test(stringLiteral.value)){this.raise(stringLiteral.start,"An export name cannot include a lone surrogate.")}return stringLiteral}return this.parseIdent(true)};pp$8.adaptDirectivePrologue=function(statements){for(var i=0;i=6&&node){switch(node.type){case"Identifier":if(this.inAsync&&node.name==="await"){this.raise(node.start,"Cannot use 'await' as identifier inside an async function")}break;case"ObjectPattern":case"ArrayPattern":case"AssignmentPattern":case"RestElement":break;case"ObjectExpression":node.type="ObjectPattern";if(refDestructuringErrors){this.checkPatternErrors(refDestructuringErrors,true)}for(var i=0,list=node.properties;i=8&&!containsEsc&&id.name==="async"&&!this.canInsertSemicolon()&&this.eat(types$1._function)){this.overrideContext(types.f_expr);return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true,forInit)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types$1.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false,forInit)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types$1.name&&!containsEsc&&(!this.potentialArrowInForAwait||this.value!=="of"||this.containsEsc)){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types$1.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true,forInit)}}return id;case types$1.regexp:var value=this.value;node=this.parseLiteral(value.value);node.regex={pattern:value.pattern,flags:value.flags};return node;case types$1.num:case types$1.string:return this.parseLiteral(this.value);case types$1._null:case types$1._true:case types$1._false:node=this.startNode();node.value=this.type===types$1._null?null:this.type===types$1._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types$1.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow,forInit);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types$1.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types$1.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types$1.braceL:this.overrideContext(types.b_expr);return this.parseObj(false,refDestructuringErrors);case types$1._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types$1._class:return this.parseClass(this.startNode(),false);case types$1._new:return this.parseNew();case types$1.backQuote:return this.parseTemplate();case types$1._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$5.parseExprImport=function(){var node=this.startNode();if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword import")}var meta=this.parseIdent(true);switch(this.type){case types$1.parenL:return this.parseDynamicImport(node);case types$1.dot:node.meta=meta;return this.parseImportMeta(node);default:this.unexpected()}};pp$5.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types$1.parenR)){var errorPos=this.start;if(this.eat(types$1.comma)&&this.eat(types$1.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$5.parseImportMeta=function(node){this.next();var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="meta"){this.raiseRecoverable(node.property.start,"The only valid meta property for import is 'import.meta'")}if(containsEsc){this.raiseRecoverable(node.start,"'import.meta' must not contain escaped characters")}if(this.options.sourceType!=="module"&&!this.options.allowImportExportEverywhere){this.raiseRecoverable(node.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(node,"MetaProperty")};pp$5.parseLiteral=function(value){var node=this.startNode();node.value=value;node.raw=this.input.slice(this.start,this.end);if(node.raw.charCodeAt(node.raw.length-1)===110){node.bigint=node.raw.slice(0,-1).replace(/_/g,"")}this.next();return this.finishNode(node,"Literal")};pp$5.parseParenExpression=function(){this.expect(types$1.parenL);var val=this.parseExpression();this.expect(types$1.parenR);return val};pp$5.parseParenAndDistinguishExpression=function(canBeArrow,forInit){var startPos=this.start,startLoc=this.startLoc,val,allowTrailingComma=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var innerStartPos=this.start,innerStartLoc=this.startLoc;var exprList=[],first=true,lastIsComma=false;var refDestructuringErrors=new DestructuringErrors,oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,spreadStart;this.yieldPos=0;this.awaitPos=0;while(this.type!==types$1.parenR){first?first=false:this.expect(types$1.comma);if(allowTrailingComma&&this.afterTrailingComma(types$1.parenR,true)){lastIsComma=true;break}else if(this.type===types$1.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types$1.comma){this.raise(this.start,"Comma is not permitted after the rest element")}break}else{exprList.push(this.parseMaybeAssign(false,refDestructuringErrors,this.parseParenItem))}}var innerEndPos=this.lastTokEnd,innerEndLoc=this.lastTokEndLoc;this.expect(types$1.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types$1.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList,forInit)}if(!exprList.length||lastIsComma){this.unexpected(this.lastTokStart)}if(spreadStart){this.unexpected(spreadStart)}this.checkExpressionErrors(refDestructuringErrors,true);this.yieldPos=oldYieldPos||this.yieldPos;this.awaitPos=oldAwaitPos||this.awaitPos;if(exprList.length>1){val=this.startNodeAt(innerStartPos,innerStartLoc);val.expressions=exprList;this.finishNodeAt(val,"SequenceExpression",innerEndPos,innerEndLoc)}else{val=exprList[0]}}else{val=this.parseParenExpression()}if(this.options.preserveParens){var par=this.startNodeAt(startPos,startLoc);par.expression=val;return this.finishNode(par,"ParenthesizedExpression")}else{return val}};pp$5.parseParenItem=function(item){return item};pp$5.parseParenArrowList=function(startPos,startLoc,exprList,forInit){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList,false,forInit)};var empty=[];pp$5.parseNew=function(){if(this.containsEsc){this.raiseRecoverable(this.start,"Escape sequence in keyword new")}var node=this.startNode();var meta=this.parseIdent(true);if(this.options.ecmaVersion>=6&&this.eat(types$1.dot)){node.meta=meta;var containsEsc=this.containsEsc;node.property=this.parseIdent(true);if(node.property.name!=="target"){this.raiseRecoverable(node.property.start,"The only valid meta property for new is 'new.target'")}if(containsEsc){this.raiseRecoverable(node.start,"'new.target' must not contain escaped characters")}if(!this.allowNewDotTarget){this.raiseRecoverable(node.start,"'new.target' can only be used in functions and class static block")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types$1._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true,false);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types$1.parenL)){node.arguments=this.parseExprList(types$1.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty}return this.finishNode(node,"NewExpression")};pp$5.parseTemplateElement=function(ref){var isTagged=ref.isTagged;var elem=this.startNode();if(this.type===types$1.invalidTemplate){if(!isTagged){this.raiseRecoverable(this.start,"Bad escape sequence in untagged template literal")}elem.value={raw:this.value,cooked:null}}else{elem.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,"\n"),cooked:this.value}}this.next();elem.tail=this.type===types$1.backQuote;return this.finishNode(elem,"TemplateElement")};pp$5.parseTemplate=function(ref){if(ref===void 0)ref={};var isTagged=ref.isTagged;if(isTagged===void 0)isTagged=false;var node=this.startNode();this.next();node.expressions=[];var curElt=this.parseTemplateElement({isTagged:isTagged});node.quasis=[curElt];while(!curElt.tail){if(this.type===types$1.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types$1.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types$1.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged:isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$5.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types$1.name||this.type===types$1.num||this.type===types$1.string||this.type===types$1.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types$1.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$5.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types$1.braceR)){if(!first){this.expect(types$1.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types$1.braceR)){break}}else{first=false}var prop=this.parseProperty(isPattern,refDestructuringErrors);if(!isPattern){this.checkPropClash(prop,propHash,refDestructuringErrors)}node.properties.push(prop)}return this.finishNode(node,isPattern?"ObjectPattern":"ObjectExpression")};pp$5.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types$1.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types$1.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types$1.parenL&&refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0){refDestructuringErrors.parenthesizedAssign=this.start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=this.start}}prop.argument=this.parseMaybeAssign(false,refDestructuringErrors);if(this.type===types$1.comma&&refDestructuringErrors&&refDestructuringErrors.trailingComma<0){refDestructuringErrors.trailingComma=this.start}return this.finishNode(prop,"SpreadElement")}if(this.options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;if(isPattern||refDestructuringErrors){startPos=this.start;startLoc=this.startLoc}if(!isPattern){isGenerator=this.eat(types$1.star)}}var containsEsc=this.containsEsc;this.parsePropertyName(prop);if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=8&&!isGenerator&&this.isAsyncProp(prop)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types$1.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$5.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types$1.colon){this.unexpected()}if(this.eat(types$1.colon)){prop.value=isPattern?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(false,refDestructuringErrors);prop.kind="init"}else if(this.options.ecmaVersion>=6&&this.type===types$1.parenL){if(isPattern){this.unexpected()}prop.kind="init";prop.method=true;prop.value=this.parseMethod(isGenerator,isAsync)}else if(!isPattern&&!containsEsc&&this.options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")&&(this.type!==types$1.comma&&this.type!==types$1.braceR&&this.type!==types$1.eq)){if(isGenerator||isAsync){this.unexpected()}prop.kind=prop.key.name;this.parsePropertyName(prop);prop.value=this.parseMethod(false);var paramCount=prop.kind==="get"?0:1;if(prop.value.params.length!==paramCount){var start=prop.value.start;if(prop.kind==="get"){this.raiseRecoverable(start,"getter should have no params")}else{this.raiseRecoverable(start,"setter should have exactly one param")}}else{if(prop.kind==="set"&&prop.value.params[0].type==="RestElement"){this.raiseRecoverable(prop.value.params[0].start,"Setter cannot use rest params")}}}else if(this.options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){if(isGenerator||isAsync){this.unexpected()}this.checkUnreserved(prop.key);if(prop.key.name==="await"&&!this.awaitIdentPos){this.awaitIdentPos=startPos}prop.kind="init";if(isPattern){prop.value=this.parseMaybeDefault(startPos,startLoc,this.copyNode(prop.key))}else if(this.type===types$1.eq&&refDestructuringErrors){if(refDestructuringErrors.shorthandAssign<0){refDestructuringErrors.shorthandAssign=this.start}prop.value=this.parseMaybeDefault(startPos,startLoc,this.copyNode(prop.key))}else{prop.value=this.copyNode(prop.key)}prop.shorthand=true}else{this.unexpected()}};pp$5.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types$1.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types$1.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types$1.num||this.type===types$1.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$5.initFunction=function(node){node.id=null;if(this.options.ecmaVersion>=6){node.generator=node.expression=false}if(this.options.ecmaVersion>=8){node.async=false}};pp$5.parseMethod=function(isGenerator,isAsync,allowDirectSuper){var node=this.startNode(),oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.initFunction(node);if(this.options.ecmaVersion>=6){node.generator=isGenerator}if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;this.enterScope(functionFlags(isAsync,node.generator)|SCOPE_SUPER|(allowDirectSuper?SCOPE_DIRECT_SUPER:0));this.expect(types$1.parenL);node.params=this.parseBindingList(types$1.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$5.parseArrowExpression=function(node,params,isAsync,forInit){var oldYieldPos=this.yieldPos,oldAwaitPos=this.awaitPos,oldAwaitIdentPos=this.awaitIdentPos;this.enterScope(functionFlags(isAsync,false)|SCOPE_ARROW);this.initFunction(node);if(this.options.ecmaVersion>=8){node.async=!!isAsync}this.yieldPos=0;this.awaitPos=0;this.awaitIdentPos=0;node.params=this.toAssignableList(params,true);this.parseFunctionBody(node,true,false,forInit);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$5.parseFunctionBody=function(node,isArrowFunction,isMethod,forInit){var isExpression=isArrowFunction&&this.type!==types$1.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign(forInit);node.expression=true;this.checkParams(node,false)}else{var nonSimple=this.options.ecmaVersion>=7&&!this.isSimpleParamList(node.params);if(!oldStrict||nonSimple){useStrict=this.strictDirective(this.end);if(useStrict&&nonSimple){this.raiseRecoverable(node.start,"Illegal 'use strict' directive in function with non-simple parameter list")}}var oldLabels=this.labels;this.labels=[];if(useStrict){this.strict=true}this.checkParams(node,!oldStrict&&!useStrict&&!isArrowFunction&&!isMethod&&this.isSimpleParamList(node.params));if(this.strict&&node.id){this.checkLValSimple(node.id,BIND_OUTSIDE)}node.body=this.parseBlock(false,undefined,useStrict&&!oldStrict);node.expression=false;this.adaptDirectivePrologue(node.body.body);this.labels=oldLabels}this.exitScope()};pp$5.isSimpleParamList=function(params){for(var i=0,list=params;i-1||scope.functions.indexOf(name)>-1||scope.var.indexOf(name)>-1;scope.lexical.push(name);if(this.inModule&&scope.flags&SCOPE_TOP){delete this.undefinedExports[name]}}else if(bindingType===BIND_SIMPLE_CATCH){var scope$1=this.currentScope();scope$1.lexical.push(name)}else if(bindingType===BIND_FUNCTION){var scope$2=this.currentScope();if(this.treatFunctionsAsVar){redeclared=scope$2.lexical.indexOf(name)>-1}else{redeclared=scope$2.lexical.indexOf(name)>-1||scope$2.var.indexOf(name)>-1}scope$2.functions.push(name)}else{for(var i=this.scopeStack.length-1;i>=0;--i){var scope$3=this.scopeStack[i];if(scope$3.lexical.indexOf(name)>-1&&!(scope$3.flags&SCOPE_SIMPLE_CATCH&&scope$3.lexical[0]===name)||!this.treatFunctionsAsVarInScope(scope$3)&&scope$3.functions.indexOf(name)>-1){redeclared=true;break}scope$3.var.push(name);if(this.inModule&&scope$3.flags&SCOPE_TOP){delete this.undefinedExports[name]}if(scope$3.flags&SCOPE_VAR){break}}}if(redeclared){this.raiseRecoverable(pos,"Identifier '"+name+"' has already been declared")}};pp$3.checkLocalExport=function(id){if(this.scopeStack[0].lexical.indexOf(id.name)===-1&&this.scopeStack[0].var.indexOf(id.name)===-1){this.undefinedExports[id.name]=id}};pp$3.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$3.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$3.currentThisScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR&&!(scope.flags&SCOPE_ARROW)){return scope}}};var Node=function Node(parser,pos,loc){this.type="";this.start=pos;this.end=0;if(parser.options.locations){this.loc=new SourceLocation(parser,loc)}if(parser.options.directSourceFile){this.sourceFile=parser.options.directSourceFile}if(parser.options.ranges){this.range=[pos,0]}};var pp$2=Parser.prototype;pp$2.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$2.startNodeAt=function(pos,loc){return new Node(this,pos,loc)};function finishNodeAt(node,type,pos,loc){node.type=type;node.end=pos;if(this.options.locations){node.loc.end=loc}if(this.options.ranges){node.range[1]=pos}return node}pp$2.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$2.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};pp$2.copyNode=function(node){var newNode=new Node(this,node.start,this.startLoc);for(var prop in node){newNode[prop]=node[prop]}return newNode};var ecma9BinaryProperties="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";var ecma10BinaryProperties=ecma9BinaryProperties+" Extended_Pictographic";var ecma11BinaryProperties=ecma10BinaryProperties;var ecma12BinaryProperties=ecma11BinaryProperties+" EBase EComp EMod EPres ExtPict";var ecma13BinaryProperties=ecma12BinaryProperties;var unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties,12:ecma12BinaryProperties,13:ecma13BinaryProperties};var unicodeGeneralCategoryValues="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";var ecma9ScriptValues="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 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 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 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 Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";var ecma10ScriptValues=ecma9ScriptValues+" Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";var ecma11ScriptValues=ecma10ScriptValues+" Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";var ecma12ScriptValues=ecma11ScriptValues+" Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";var ecma13ScriptValues=ecma12ScriptValues+" Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith";var unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues,12:ecma12ScriptValues,13:ecma13ScriptValues};var data={};function buildUnicodeData(ecmaVersion){var d=data[ecmaVersion]={binary:wordsRegexp(unicodeBinaryProperties[ecmaVersion]+" "+unicodeGeneralCategoryValues),nonBinary:{General_Category:wordsRegexp(unicodeGeneralCategoryValues),Script:wordsRegexp(unicodeScriptValues[ecmaVersion])}};d.nonBinary.Script_Extensions=d.nonBinary.Script;d.nonBinary.gc=d.nonBinary.General_Category;d.nonBinary.sc=d.nonBinary.Script;d.nonBinary.scx=d.nonBinary.Script_Extensions}for(var i=0,list=[9,10,11,12,13];i=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"")+(parser.options.ecmaVersion>=13?"d":"");this.unicodeProperties=data[parser.options.ecmaVersion>=13?13:parser.options.ecmaVersion];this.source="";this.flags="";this.start=0;this.switchU=false;this.switchN=false;this.pos=0;this.lastIntValue=0;this.lastStringValue="";this.lastAssertionIsQuantifiable=false;this.numCapturingParens=0;this.maxBackReference=0;this.groupNames=[];this.backReferenceNames=[]};RegExpValidationState.prototype.reset=function reset(start,pattern,flags){var unicode=flags.indexOf("u")!==-1;this.start=start|0;this.source=pattern+"";this.flags=flags;this.switchU=unicode&&this.parser.options.ecmaVersion>=6;this.switchN=unicode&&this.parser.options.ecmaVersion>=9};RegExpValidationState.prototype.raise=function raise(message){this.parser.raiseRecoverable(this.start,"Invalid regular expression: /"+this.source+"/: "+message)};RegExpValidationState.prototype.at=function at(i,forceU){if(forceU===void 0)forceU=false;var s=this.source;var l=s.length;if(i>=l){return-1}var c=s.charCodeAt(i);if(!(forceU||this.switchU)||c<=55295||c>=57344||i+1>=l){return c}var next=s.charCodeAt(i+1);return next>=56320&&next<=57343?(c<<10)+next-56613888:c};RegExpValidationState.prototype.nextIndex=function nextIndex(i,forceU){if(forceU===void 0)forceU=false;var s=this.source;var l=s.length;if(i>=l){return l}var c=s.charCodeAt(i),next;if(!(forceU||this.switchU)||c<=55295||c>=57344||i+1>=l||(next=s.charCodeAt(i+1))<56320||next>57343){return i+1}return i+2};RegExpValidationState.prototype.current=function current(forceU){if(forceU===void 0)forceU=false;return this.at(this.pos,forceU)};RegExpValidationState.prototype.lookahead=function lookahead(forceU){if(forceU===void 0)forceU=false;return this.at(this.nextIndex(this.pos,forceU),forceU)};RegExpValidationState.prototype.advance=function advance(forceU){if(forceU===void 0)forceU=false;this.pos=this.nextIndex(this.pos,forceU)};RegExpValidationState.prototype.eat=function eat(ch,forceU){if(forceU===void 0)forceU=false;if(this.current(forceU)===ch){this.advance(forceU);return true}return false};function codePointToString$1(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$1.validateRegExpFlags=function(state){var validFlags=state.validFlags;var flags=state.flags;for(var i=0;i-1){this.raise(state.start,"Duplicate regular expression flag")}}};pp$1.validateRegExpPattern=function(state){this.regexp_pattern(state);if(!state.switchN&&this.options.ecmaVersion>=9&&state.groupNames.length>0){state.switchN=true;this.regexp_pattern(state)}};pp$1.regexp_pattern=function(state){state.pos=0;state.lastIntValue=0;state.lastStringValue="";state.lastAssertionIsQuantifiable=false;state.numCapturingParens=0;state.maxBackReference=0;state.groupNames.length=0;state.backReferenceNames.length=0;this.regexp_disjunction(state);if(state.pos!==state.source.length){if(state.eat(41)){state.raise("Unmatched ')'")}if(state.eat(93)||state.eat(125)){state.raise("Lone quantifier brackets")}}if(state.maxBackReference>state.numCapturingParens){state.raise("Invalid escape")}for(var i=0,list=state.backReferenceNames;i=9){lookbehind=state.eat(60)}if(state.eat(61)||state.eat(33)){this.regexp_disjunction(state);if(!state.eat(41)){state.raise("Unterminated group")}state.lastAssertionIsQuantifiable=!lookbehind;return true}}state.pos=start;return false};pp$1.regexp_eatQuantifier=function(state,noError){if(noError===void 0)noError=false;if(this.regexp_eatQuantifierPrefix(state,noError)){state.eat(63);return true}return false};pp$1.regexp_eatQuantifierPrefix=function(state,noError){return state.eat(42)||state.eat(43)||state.eat(63)||this.regexp_eatBracedQuantifier(state,noError)};pp$1.regexp_eatBracedQuantifier=function(state,noError){var start=state.pos;if(state.eat(123)){var min=0,max=-1;if(this.regexp_eatDecimalDigits(state)){min=state.lastIntValue;if(state.eat(44)&&this.regexp_eatDecimalDigits(state)){max=state.lastIntValue}if(state.eat(125)){if(max!==-1&&max=9){this.regexp_groupSpecifier(state)}else if(state.current()===63){state.raise("Invalid group")}this.regexp_disjunction(state);if(state.eat(41)){state.numCapturingParens+=1;return true}state.raise("Unterminated group")}return false};pp$1.regexp_eatExtendedAtom=function(state){return state.eat(46)||this.regexp_eatReverseSolidusAtomEscape(state)||this.regexp_eatCharacterClass(state)||this.regexp_eatUncapturingGroup(state)||this.regexp_eatCapturingGroup(state)||this.regexp_eatInvalidBracedQuantifier(state)||this.regexp_eatExtendedPatternCharacter(state)};pp$1.regexp_eatInvalidBracedQuantifier=function(state){if(this.regexp_eatBracedQuantifier(state,true)){state.raise("Nothing to repeat")}return false};pp$1.regexp_eatSyntaxCharacter=function(state){var ch=state.current();if(isSyntaxCharacter(ch)){state.lastIntValue=ch;state.advance();return true}return false};function isSyntaxCharacter(ch){return ch===36||ch>=40&&ch<=43||ch===46||ch===63||ch>=91&&ch<=94||ch>=123&&ch<=125}pp$1.regexp_eatPatternCharacters=function(state){var start=state.pos;var ch=0;while((ch=state.current())!==-1&&!isSyntaxCharacter(ch)){state.advance()}return state.pos!==start};pp$1.regexp_eatExtendedPatternCharacter=function(state){var ch=state.current();if(ch!==-1&&ch!==36&&!(ch>=40&&ch<=43)&&ch!==46&&ch!==63&&ch!==91&&ch!==94&&ch!==124){state.advance();return true}return false};pp$1.regexp_groupSpecifier=function(state){if(state.eat(63)){if(this.regexp_eatGroupName(state)){if(state.groupNames.indexOf(state.lastStringValue)!==-1){state.raise("Duplicate capture group name")}state.groupNames.push(state.lastStringValue);return}state.raise("Invalid group")}};pp$1.regexp_eatGroupName=function(state){state.lastStringValue="";if(state.eat(60)){if(this.regexp_eatRegExpIdentifierName(state)&&state.eat(62)){return true}state.raise("Invalid capture group name")}return false};pp$1.regexp_eatRegExpIdentifierName=function(state){state.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state)){state.lastStringValue+=codePointToString$1(state.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state)){state.lastStringValue+=codePointToString$1(state.lastIntValue)}return true}return false};pp$1.regexp_eatRegExpIdentifierStart=function(state){var start=state.pos;var forceU=this.options.ecmaVersion>=11;var ch=state.current(forceU);state.advance(forceU);if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state,forceU)){ch=state.lastIntValue}if(isRegExpIdentifierStart(ch)){state.lastIntValue=ch;return true}state.pos=start;return false};function isRegExpIdentifierStart(ch){return isIdentifierStart(ch,true)||ch===36||ch===95}pp$1.regexp_eatRegExpIdentifierPart=function(state){var start=state.pos;var forceU=this.options.ecmaVersion>=11;var ch=state.current(forceU);state.advance(forceU);if(ch===92&&this.regexp_eatRegExpUnicodeEscapeSequence(state,forceU)){ch=state.lastIntValue}if(isRegExpIdentifierPart(ch)){state.lastIntValue=ch;return true}state.pos=start;return false};function isRegExpIdentifierPart(ch){return isIdentifierChar(ch,true)||ch===36||ch===95||ch===8204||ch===8205}pp$1.regexp_eatAtomEscape=function(state){if(this.regexp_eatBackReference(state)||this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)||state.switchN&&this.regexp_eatKGroupName(state)){return true}if(state.switchU){if(state.current()===99){state.raise("Invalid unicode escape")}state.raise("Invalid escape")}return false};pp$1.regexp_eatBackReference=function(state){var start=state.pos;if(this.regexp_eatDecimalEscape(state)){var n=state.lastIntValue;if(state.switchU){if(n>state.maxBackReference){state.maxBackReference=n}return true}if(n<=state.numCapturingParens){return true}state.pos=start}return false};pp$1.regexp_eatKGroupName=function(state){if(state.eat(107)){if(this.regexp_eatGroupName(state)){state.backReferenceNames.push(state.lastStringValue);return true}state.raise("Invalid named reference")}return false};pp$1.regexp_eatCharacterEscape=function(state){return this.regexp_eatControlEscape(state)||this.regexp_eatCControlLetter(state)||this.regexp_eatZero(state)||this.regexp_eatHexEscapeSequence(state)||this.regexp_eatRegExpUnicodeEscapeSequence(state,false)||!state.switchU&&this.regexp_eatLegacyOctalEscapeSequence(state)||this.regexp_eatIdentityEscape(state)};pp$1.regexp_eatCControlLetter=function(state){var start=state.pos;if(state.eat(99)){if(this.regexp_eatControlLetter(state)){return true}state.pos=start}return false};pp$1.regexp_eatZero=function(state){if(state.current()===48&&!isDecimalDigit(state.lookahead())){state.lastIntValue=0;state.advance();return true}return false};pp$1.regexp_eatControlEscape=function(state){var ch=state.current();if(ch===116){state.lastIntValue=9;state.advance();return true}if(ch===110){state.lastIntValue=10;state.advance();return true}if(ch===118){state.lastIntValue=11;state.advance();return true}if(ch===102){state.lastIntValue=12;state.advance();return true}if(ch===114){state.lastIntValue=13;state.advance();return true}return false};pp$1.regexp_eatControlLetter=function(state){var ch=state.current();if(isControlLetter(ch)){state.lastIntValue=ch%32;state.advance();return true}return false};function isControlLetter(ch){return ch>=65&&ch<=90||ch>=97&&ch<=122}pp$1.regexp_eatRegExpUnicodeEscapeSequence=function(state,forceU){if(forceU===void 0)forceU=false;var start=state.pos;var switchU=forceU||state.switchU;if(state.eat(117)){if(this.regexp_eatFixedHexDigits(state,4)){var lead=state.lastIntValue;if(switchU&&lead>=55296&&lead<=56319){var leadSurrogateEnd=state.pos;if(state.eat(92)&&state.eat(117)&&this.regexp_eatFixedHexDigits(state,4)){var trail=state.lastIntValue;if(trail>=56320&&trail<=57343){state.lastIntValue=(lead-55296)*1024+(trail-56320)+65536;return true}}state.pos=leadSurrogateEnd;state.lastIntValue=lead}return true}if(switchU&&state.eat(123)&&this.regexp_eatHexDigits(state)&&state.eat(125)&&isValidUnicode(state.lastIntValue)){return true}if(switchU){state.raise("Invalid unicode escape")}state.pos=start}return false};function isValidUnicode(ch){return ch>=0&&ch<=1114111}pp$1.regexp_eatIdentityEscape=function(state){if(state.switchU){if(this.regexp_eatSyntaxCharacter(state)){return true}if(state.eat(47)){state.lastIntValue=47;return true}return false}var ch=state.current();if(ch!==99&&(!state.switchN||ch!==107)){state.lastIntValue=ch;state.advance();return true}return false};pp$1.regexp_eatDecimalEscape=function(state){state.lastIntValue=0;var ch=state.current();if(ch>=49&&ch<=57){do{state.lastIntValue=10*state.lastIntValue+(ch-48);state.advance()}while((ch=state.current())>=48&&ch<=57);return true}return false};pp$1.regexp_eatCharacterClassEscape=function(state){var ch=state.current();if(isCharacterClassEscape(ch)){state.lastIntValue=-1;state.advance();return true}if(state.switchU&&this.options.ecmaVersion>=9&&(ch===80||ch===112)){state.lastIntValue=-1;state.advance();if(state.eat(123)&&this.regexp_eatUnicodePropertyValueExpression(state)&&state.eat(125)){return true}state.raise("Invalid property name")}return false};function isCharacterClassEscape(ch){return ch===100||ch===68||ch===115||ch===83||ch===119||ch===87}pp$1.regexp_eatUnicodePropertyValueExpression=function(state){var start=state.pos;if(this.regexp_eatUnicodePropertyName(state)&&state.eat(61)){var name=state.lastStringValue;if(this.regexp_eatUnicodePropertyValue(state)){var value=state.lastStringValue;this.regexp_validateUnicodePropertyNameAndValue(state,name,value);return true}}state.pos=start;if(this.regexp_eatLoneUnicodePropertyNameOrValue(state)){var nameOrValue=state.lastStringValue;this.regexp_validateUnicodePropertyNameOrValue(state,nameOrValue);return true}return false};pp$1.regexp_validateUnicodePropertyNameAndValue=function(state,name,value){if(!hasOwn(state.unicodeProperties.nonBinary,name)){state.raise("Invalid property name")}if(!state.unicodeProperties.nonBinary[name].test(value)){state.raise("Invalid property value")}};pp$1.regexp_validateUnicodePropertyNameOrValue=function(state,nameOrValue){if(!state.unicodeProperties.binary.test(nameOrValue)){state.raise("Invalid property name")}};pp$1.regexp_eatUnicodePropertyName=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state.current())){state.lastStringValue+=codePointToString$1(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$1.regexp_eatUnicodePropertyValue=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state.current())){state.lastStringValue+=codePointToString$1(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$1.regexp_eatLoneUnicodePropertyNameOrValue=function(state){return this.regexp_eatUnicodePropertyValue(state)};pp$1.regexp_eatCharacterClass=function(state){if(state.eat(91)){state.eat(94);this.regexp_classRanges(state);if(state.eat(93)){return true}state.raise("Unterminated character class")}return false};pp$1.regexp_classRanges=function(state){while(this.regexp_eatClassAtom(state)){var left=state.lastIntValue;if(state.eat(45)&&this.regexp_eatClassAtom(state)){var right=state.lastIntValue;if(state.switchU&&(left===-1||right===-1)){state.raise("Invalid character class")}if(left!==-1&&right!==-1&&left>right){state.raise("Range out of order in character class")}}}};pp$1.regexp_eatClassAtom=function(state){var start=state.pos;if(state.eat(92)){if(this.regexp_eatClassEscape(state)){return true}if(state.switchU){var ch$1=state.current();if(ch$1===99||isOctalDigit(ch$1)){state.raise("Invalid class escape")}state.raise("Invalid escape")}state.pos=start}var ch=state.current();if(ch!==93){state.lastIntValue=ch;state.advance();return true}return false};pp$1.regexp_eatClassEscape=function(state){var start=state.pos;if(state.eat(98)){state.lastIntValue=8;return true}if(state.switchU&&state.eat(45)){state.lastIntValue=45;return true}if(!state.switchU&&state.eat(99)){if(this.regexp_eatClassControlLetter(state)){return true}state.pos=start}return this.regexp_eatCharacterClassEscape(state)||this.regexp_eatCharacterEscape(state)};pp$1.regexp_eatClassControlLetter=function(state){var ch=state.current();if(isDecimalDigit(ch)||ch===95){state.lastIntValue=ch%32;state.advance();return true}return false};pp$1.regexp_eatHexEscapeSequence=function(state){var start=state.pos;if(state.eat(120)){if(this.regexp_eatFixedHexDigits(state,2)){return true}if(state.switchU){state.raise("Invalid escape")}state.pos=start}return false};pp$1.regexp_eatDecimalDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isDecimalDigit(ch=state.current())){state.lastIntValue=10*state.lastIntValue+(ch-48);state.advance()}return state.pos!==start};function isDecimalDigit(ch){return ch>=48&&ch<=57}pp$1.regexp_eatHexDigits=function(state){var start=state.pos;var ch=0;state.lastIntValue=0;while(isHexDigit(ch=state.current())){state.lastIntValue=16*state.lastIntValue+hexToInt(ch);state.advance()}return state.pos!==start};function isHexDigit(ch){return ch>=48&&ch<=57||ch>=65&&ch<=70||ch>=97&&ch<=102}function hexToInt(ch){if(ch>=65&&ch<=70){return 10+(ch-65)}if(ch>=97&&ch<=102){return 10+(ch-97)}return ch-48}pp$1.regexp_eatLegacyOctalEscapeSequence=function(state){if(this.regexp_eatOctalDigit(state)){var n1=state.lastIntValue;if(this.regexp_eatOctalDigit(state)){var n2=state.lastIntValue;if(n1<=3&&this.regexp_eatOctalDigit(state)){state.lastIntValue=n1*64+n2*8+state.lastIntValue}else{state.lastIntValue=n1*8+n2}}else{state.lastIntValue=n1}return true}return false};pp$1.regexp_eatOctalDigit=function(state){var ch=state.current();if(isOctalDigit(ch)){state.lastIntValue=ch-48;state.advance();return true}state.lastIntValue=0;return false};function isOctalDigit(ch){return ch>=48&&ch<=55}pp$1.regexp_eatFixedHexDigits=function(state,length){var start=state.pos;state.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types$1.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=56320){return code}var next=this.input.charCodeAt(this.pos+1);return next<=56319||next>=57344?code:(code<<10)+next-56613888};pp.skipBlockComment=function(){var startLoc=this.options.onComment&&this.curPosition();var start=this.pos,end=this.input.indexOf("*/",this.pos+=2);if(end===-1){this.raise(this.pos-2,"Unterminated comment")}this.pos=end+2;if(this.options.locations){for(var nextBreak=void 0,pos=start;(nextBreak=nextLineBreak(this.input,pos,this.pos))>-1;){++this.curLine;pos=this.lineStart=nextBreak}}if(this.options.onComment){this.options.onComment(true,this.input.slice(start+2,end),start,this.pos,startLoc,this.curPosition())}};pp.skipLineComment=function(startSkip){var start=this.pos;var startLoc=this.options.onComment&&this.curPosition();var ch=this.input.charCodeAt(this.pos+=startSkip);while(this.pos8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp.finishToken=function(type,val){this.end=this.pos;if(this.options.locations){this.endLoc=this.curPosition()}var prevType=this.type;this.type=type;this.value=val;this.updateContext(prevType)};pp.readToken_dot=function(){var next=this.input.charCodeAt(this.pos+1);if(next>=48&&next<=57){return this.readNumber(true)}var next2=this.input.charCodeAt(this.pos+2);if(this.options.ecmaVersion>=6&&next===46&&next2===46){this.pos+=3;return this.finishToken(types$1.ellipsis)}else{++this.pos;return this.finishToken(types$1.dot)}};pp.readToken_slash=function(){var next=this.input.charCodeAt(this.pos+1);if(this.exprAllowed){++this.pos;return this.readRegexp()}if(next===61){return this.finishOp(types$1.assign,2)}return this.finishOp(types$1.slash,1)};pp.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types$1.star:types$1.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types$1.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types$1.assign,size+1)}return this.finishOp(tokentype,size)};pp.readToken_pipe_amp=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(this.options.ecmaVersion>=12){var next2=this.input.charCodeAt(this.pos+2);if(next2===61){return this.finishOp(types$1.assign,3)}}return this.finishOp(code===124?types$1.logicalOR:types$1.logicalAND,2)}if(next===61){return this.finishOp(types$1.assign,2)}return this.finishOp(code===124?types$1.bitwiseOR:types$1.bitwiseAND,1)};pp.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types$1.assign,2)}return this.finishOp(types$1.bitwiseXOR,1)};pp.readToken_plus_min=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===code){if(next===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||lineBreak.test(this.input.slice(this.lastTokEnd,this.pos)))){this.skipLineComment(3);this.skipSpace();return this.nextToken()}return this.finishOp(types$1.incDec,2)}if(next===61){return this.finishOp(types$1.assign,2)}return this.finishOp(types$1.plusMin,1)};pp.readToken_lt_gt=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;if(next===code){size=code===62&&this.input.charCodeAt(this.pos+2)===62?3:2;if(this.input.charCodeAt(this.pos+size)===61){return this.finishOp(types$1.assign,size+1)}return this.finishOp(types$1.bitShift,size)}if(next===33&&code===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45){this.skipLineComment(4);this.skipSpace();return this.nextToken()}if(next===61){size=2}return this.finishOp(types$1.relational,size)};pp.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types$1.equality,this.input.charCodeAt(this.pos+2)===61?3:2)}if(code===61&&next===62&&this.options.ecmaVersion>=6){this.pos+=2;return this.finishToken(types$1.arrow)}return this.finishOp(code===61?types$1.eq:types$1.prefix,1)};pp.readToken_question=function(){var ecmaVersion=this.options.ecmaVersion;if(ecmaVersion>=11){var next=this.input.charCodeAt(this.pos+1);if(next===46){var next2=this.input.charCodeAt(this.pos+2);if(next2<48||next2>57){return this.finishOp(types$1.questionDot,2)}}if(next===63){if(ecmaVersion>=12){var next2$1=this.input.charCodeAt(this.pos+2);if(next2$1===61){return this.finishOp(types$1.assign,3)}}return this.finishOp(types$1.coalesce,2)}}return this.finishOp(types$1.question,1)};pp.readToken_numberSign=function(){var ecmaVersion=this.options.ecmaVersion;var code=35;if(ecmaVersion>=13){++this.pos;code=this.fullCharCodeAtPos();if(isIdentifierStart(code,true)||code===92){return this.finishToken(types$1.privateId,this.readWord1())}}this.raise(this.pos,"Unexpected character '"+codePointToString(code)+"'")};pp.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types$1.parenL);case 41:++this.pos;return this.finishToken(types$1.parenR);case 59:++this.pos;return this.finishToken(types$1.semi);case 44:++this.pos;return this.finishToken(types$1.comma);case 91:++this.pos;return this.finishToken(types$1.bracketL);case 93:++this.pos;return this.finishToken(types$1.bracketR);case 123:++this.pos;return this.finishToken(types$1.braceL);case 125:++this.pos;return this.finishToken(types$1.braceR);case 58:++this.pos;return this.finishToken(types$1.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types$1.backQuote);case 48:var next=this.input.charCodeAt(this.pos+1);if(next===120||next===88){return this.readRadixNumber(16)}if(this.options.ecmaVersion>=6){if(next===111||next===79){return this.readRadixNumber(8)}if(next===98||next===66){return this.readRadixNumber(2)}}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(false);case 34:case 39:return this.readString(code);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(code);case 124:case 38:return this.readToken_pipe_amp(code);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(code);case 60:case 62:return this.readToken_lt_gt(code);case 61:case 33:return this.readToken_eq_excl(code);case 63:return this.readToken_question();case 126:return this.finishOp(types$1.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,"Unexpected character '"+codePointToString(code)+"'")};pp.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp.readRegexp=function(){var escaped,inClass,start=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(start,"Unterminated regular expression")}var ch=this.input.charAt(this.pos);if(lineBreak.test(ch)){this.raise(start,"Unterminated regular expression")}if(!escaped){if(ch==="["){inClass=true}else if(ch==="]"&&inClass){inClass=false}else if(ch==="/"&&!inClass){break}escaped=ch==="\\"}else{escaped=false}++this.pos}var pattern=this.input.slice(start,this.pos);++this.pos;var flagsStart=this.pos;var flags=this.readWord1();if(this.containsEsc){this.unexpected(flagsStart)}var state=this.regexpState||(this.regexpState=new RegExpValidationState(this));state.reset(start,pattern,flags);this.validateRegExpFlags(state);this.validateRegExpPattern(state);var value=null;try{value=new RegExp(pattern,flags)}catch(e){}return this.finishToken(types$1.regexp,{pattern:pattern,flags:flags,value:value})};pp.readInt=function(radix,len,maybeLegacyOctalNumericLiteral){var allowSeparators=this.options.ecmaVersion>=12&&len===undefined;var isLegacyOctalNumericLiteral=maybeLegacyOctalNumericLiteral&&this.input.charCodeAt(this.pos)===48;var start=this.pos,total=0,lastCode=0;for(var i=0,e=len==null?Infinity:len;i=97){val=code-97+10}else if(code>=65){val=code-65+10}else if(code>=48&&code<=57){val=code-48}else{val=Infinity}if(val>=radix){break}lastCode=code;total=total*radix+val}if(allowSeparators&&lastCode===95){this.raiseRecoverable(this.pos-1,"Numeric separator is not allowed at the last of digits")}if(this.pos===start||len!=null&&this.pos-start!==len){return null}return total};function stringToNumber(str,isLegacyOctalNumericLiteral){if(isLegacyOctalNumericLiteral){return parseInt(str,8)}return parseFloat(str.replace(/_/g,""))}function stringToBigInt(str){if(typeof BigInt!=="function"){return null}return BigInt(str.replace(/_/g,""))}pp.readRadixNumber=function(radix){var start=this.pos;this.pos+=2;var val=this.readInt(radix);if(val==null){this.raise(this.start+2,"Expected number in radix "+radix)}if(this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110){val=stringToBigInt(this.input.slice(start,this.pos));++this.pos}else if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types$1.num,val)};pp.readNumber=function(startsWithDot){var start=this.pos;if(!startsWithDot&&this.readInt(10,undefined,true)===null){this.raise(start,"Invalid number")}var octal=this.pos-start>=2&&this.input.charCodeAt(start)===48;if(octal&&this.strict){this.raise(start,"Invalid number")}var next=this.input.charCodeAt(this.pos);if(!octal&&!startsWithDot&&this.options.ecmaVersion>=11&&next===110){var val$1=stringToBigInt(this.input.slice(start,this.pos));++this.pos;if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}return this.finishToken(types$1.num,val$1)}if(octal&&/[89]/.test(this.input.slice(start,this.pos))){octal=false}if(next===46&&!octal){++this.pos;this.readInt(10);next=this.input.charCodeAt(this.pos)}if((next===69||next===101)&&!octal){next=this.input.charCodeAt(++this.pos);if(next===43||next===45){++this.pos}if(this.readInt(10)===null){this.raise(start,"Invalid number")}}if(isIdentifierStart(this.fullCharCodeAtPos())){this.raise(this.pos,"Identifier directly after number")}var val=stringToNumber(this.input.slice(start,this.pos),octal);return this.finishToken(types$1.num,val)};pp.readCodePoint=function(){var ch=this.input.charCodeAt(this.pos),code;if(ch===123){if(this.options.ecmaVersion<6){this.unexpected()}var codePos=++this.pos;code=this.readHexChar(this.input.indexOf("}",this.pos)-this.pos);++this.pos;if(code>1114111){this.invalidStringToken(codePos,"Code point out of bounds")}}else{code=this.readHexChar(4)}return code};function codePointToString(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp.readString=function(quote){var out="",chunkStart=++this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated string constant")}var ch=this.input.charCodeAt(this.pos);if(ch===quote){break}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(false);chunkStart=this.pos}else if(ch===8232||ch===8233){if(this.options.ecmaVersion<10){this.raise(this.start,"Unterminated string constant")}++this.pos;if(this.options.locations){this.curLine++;this.lineStart=this.pos}}else{if(isNewLine(ch)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types$1.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp.tryReadTemplateToken=function(){this.inTemplateElement=true;try{this.readTmplToken()}catch(err){if(err===INVALID_TEMPLATE_ESCAPE_ERROR){this.readInvalidTemplateToken()}else{throw err}}this.inTemplateElement=false};pp.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp.readTmplToken=function(){var out="",chunkStart=this.pos;for(;;){if(this.pos>=this.input.length){this.raise(this.start,"Unterminated template")}var ch=this.input.charCodeAt(this.pos);if(ch===96||ch===36&&this.input.charCodeAt(this.pos+1)===123){if(this.pos===this.start&&(this.type===types$1.template||this.type===types$1.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types$1.dollarBraceL)}else{++this.pos;return this.finishToken(types$1.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types$1.template,out)}if(ch===92){out+=this.input.slice(chunkStart,this.pos);out+=this.readEscapedChar(true);chunkStart=this.pos}else if(isNewLine(ch)){out+=this.input.slice(chunkStart,this.pos);++this.pos;switch(ch){case 13:if(this.input.charCodeAt(this.pos)===10){++this.pos}case 10:out+="\n";break;default:out+=String.fromCharCode(ch);break}if(this.options.locations){++this.curLine;this.lineStart=this.pos}chunkStart=this.pos}else{++this.pos}}};pp.readInvalidTemplateToken=function(){for(;this.pos=48&&ch<=55){var octalStr=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0];var octal=parseInt(octalStr,8);if(octal>255){octalStr=octalStr.slice(0,-1);octal=parseInt(octalStr,8)}this.pos+=octalStr.length-1;ch=this.input.charCodeAt(this.pos);if((octalStr!=="0"||ch===56||ch===57)&&(this.strict||inTemplate)){this.invalidStringToken(this.pos-1-octalStr.length,inTemplate?"Octal literal in template string":"Octal literal in strict mode")}return String.fromCharCode(octal)}if(isNewLine(ch)){return""}return String.fromCharCode(ch)}};pp.readHexChar=function(len){var codePos=this.pos;var n=this.readInt(16,len);if(n===null){this.invalidStringToken(codePos,"Bad character escape sequence")}return n};pp.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.pos * @license MIT */function compare(a,b){if(a===b){return 0}var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function truncate(s,n){if(typeof s==="string"){return s.length=0;i--){if(ka[i]!==kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected,false)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(_deepEqual(actual,expected,true)){fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}}assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}try{if(actual instanceof expected){return true}}catch(e){}if(Error.isPrototypeOf(expected)){return false}return expected.call({},actual)===true}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if(typeof block!=="function"){throw new TypeError('"block" argument must be a function')}if(typeof expected==="string"){message=expected;expected=null}actual=_tryBlock(block);message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}var userProvidedMessage=typeof message==="string";var isUnwantedException=!shouldThrow&&util.isError(actual);var isUnexpectedException=!shouldThrow&&actual&&!expected;if(isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws(true,block,error,message)};assert.doesNotThrow=function(block,error,message){_throws(false,block,error,message)};assert.ifError=function(err){if(err)throw err};function strict(value,message){if(!value)fail(value,true,message,"==",strict)}assert.strict=objectAssign(strict,assert,{equal:assert.strictEqual,deepEqual:assert.deepStrictEqual,notEqual:assert.notStrictEqual,notDeepEqual:assert.notDeepStrictEqual});assert.strict.strict=assert.strict;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"object-assign":164,"util/":22}],20:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],21:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],22:[function(require,module,exports){(function(process,global){(function(){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}));for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach((function(val,idx){hash[val]=true}));return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map((function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}))}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map((function(line){return" "+line})).join("\n").substr(2)}else{str="\n"+str.split("\n").map((function(line){return" "+line})).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce((function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":21,_process:174,inherits:20}],23:[function(require,module,exports){(function(global,factory){if(typeof define==="function"&&define.amd){define(["exports","./defaultTraveler","./attachComments"],factory)}else if(typeof exports!=="undefined"){factory(exports,require("./defaultTraveler"),require("./attachComments"))}else{var mod={exports:{}};factory(mod.exports,global.defaultTraveler,global.attachComments);global.astravel=mod.exports}})(this,(function(exports,_defaultTraveler,_attachComments){"use strict";exports.__esModule=true;exports.makeTraveler=exports.attachComments=exports.defaultTraveler=undefined;var _defaultTraveler2=_interopRequireDefault(_defaultTraveler);var _attachComments2=_interopRequireDefault(_attachComments);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function makeTraveler(properties){return _defaultTraveler2.default.makeChild(properties)}exports.defaultTraveler=_defaultTraveler2.default;exports.attachComments=_attachComments2.default;exports.makeTraveler=makeTraveler}))},{"./attachComments":24,"./defaultTraveler":25}],24:[function(require,module,exports){(function(global,factory){if(typeof define==="function"&&define.amd){define(["exports","./defaultTraveler"],factory)}else if(typeof exports!=="undefined"){factory(exports,require("./defaultTraveler"))}else{var mod={exports:{}};factory(mod.exports,global.defaultTraveler);global.attachComments=mod.exports}})(this,(function(exports,_defaultTraveler){"use strict";exports.__esModule=true;exports.default=function(node,comments){customTraveler[node.type](node,{comments:comments,index:0});return node};var _defaultTraveler2=_interopRequireDefault(_defaultTraveler);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj}}function attachComments(parent,children,findHeadingComments,state,traveler){var index=state.index,comments=state.comments;var comment=comments[index];var boundComments=void 0,trailingComments=void 0;if(comment!=null){if(children==null||children.length===0){boundComments=parent.comments!=null?parent.comments:[];while(comment!=null&&comment.end0&&arguments[0]!==undefined?arguments[0]:{};var traveler=Object.create(this);traveler.super=this;for(var key in properties){traveler[key]=properties[key]}return traveler},Program:function Program(node,state){var statements=node.body,length=statements.length;for(var i=0;i":9,"<=":9,">=":9,in:9,instanceof:9,"<<":10,">>":10,">>>":10,"+":11,"-":11,"*":12,"%":12,"/":12,"**":13};var NEEDS_PARENTHESES=17;exports.NEEDS_PARENTHESES=NEEDS_PARENTHESES;var EXPRESSIONS_PRECEDENCE={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,PrivateIdentifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,ChainExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:NEEDS_PARENTHESES,ClassExpression:NEEDS_PARENTHESES,FunctionExpression:NEEDS_PARENTHESES,ObjectExpression:NEEDS_PARENTHESES,UpdateExpression:16,UnaryExpression:15,AwaitExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,YieldExpression:2,RestElement:1};exports.EXPRESSIONS_PRECEDENCE=EXPRESSIONS_PRECEDENCE;function formatSequence(state,nodes){var generator=state.generator;state.write("(");if(nodes!=null&&nodes.length>0){generator[nodes[0].type](nodes[0],state);var length=nodes.length;for(var i=1;i0){state.write(lineEnd);for(var i=1;i0){generator.VariableDeclarator(declarations[0],state);for(var i=1;i0){state.write(lineEnd);if(writeComments&&node.comments!=null){formatComments(state,node.comments,statementIndent,lineEnd)}var length=statements.length;for(var i=0;i0){for(;i0){state.write(", ")}var specifier=specifiers[i];var type=specifier.type[6];if(type==="D"){state.write(specifier.local.name,specifier);i++}else if(type==="N"){state.write("* as "+specifier.local.name,specifier);i++}else{break}}if(i0){for(var i=0;;){var specifier=specifiers[i];var name=specifier.local.name;state.write(name,specifier);if(name!==specifier.exported.name){state.write(" as "+specifier.exported.name)}if(++i ");if(node.body.type[0]==="O"){state.write("(");this.ObjectExpression(node.body,state);state.write(")")}else{this[node.body.type](node.body,state)}},ThisExpression:function ThisExpression(node,state){state.write("this",node)},Super:function Super(node,state){state.write("super",node)},RestElement:RestElement=function RestElement(node,state){state.write("...");this[node.argument.type](node.argument,state)},SpreadElement:RestElement,YieldExpression:function YieldExpression(node,state){state.write(node.delegate?"yield*":"yield");if(node.argument){state.write(" ");this[node.argument.type](node.argument,state)}},AwaitExpression:function AwaitExpression(node,state){state.write("await ",node);formatExpression(state,node.argument,node)},TemplateLiteral:function TemplateLiteral(node,state){var quasis=node.quasis,expressions=node.expressions;state.write("`");var length=expressions.length;for(var i=0;i0){var elements=node.elements,length=elements.length;for(var i=0;;){var element=elements[i];if(element!=null){this[element.type](element,state)}if(++i0){state.write(lineEnd);if(writeComments&&node.comments!=null){formatComments(state,node.comments,propertyIndent,lineEnd)}var comma=","+lineEnd;var properties=node.properties,length=properties.length;for(var i=0;;){var property=properties[i];if(writeComments&&property.comments!=null){formatComments(state,property.comments,propertyIndent,lineEnd)}state.write(propertyIndent);this[property.type](property,state);if(++i0){var properties=node.properties,length=properties.length;for(var i=0;;){this[properties[i].type](properties[i],state);if(++i1||type[0]==="U"&&(type[1]==="n"||type[1]==="p")&&argument.prefix&&argument.operator[0]===operator&&(operator==="+"||operator==="-"))){state.write(" ")}if(needsParentheses){state.write(operator.length>1?" (":"(");this[type](argument,state);state.write(")")}else{this[type](argument,state)}}else{this[node.argument.type](node.argument,state);state.write(node.operator)}},UpdateExpression:function UpdateExpression(node,state){if(node.prefix){state.write(node.operator);this[node.argument.type](node.argument,state)}else{this[node.argument.type](node.argument,state);state.write(node.operator)}},AssignmentExpression:function AssignmentExpression(node,state){this[node.left.type](node.left,state);state.write(" "+node.operator+" ");this[node.right.type](node.right,state)},AssignmentPattern:function AssignmentPattern(node,state){this[node.left.type](node.left,state);state.write(" = ");this[node.right.type](node.right,state)},BinaryExpression:BinaryExpression=function BinaryExpression(node,state){var isIn=node.operator==="in";if(isIn){state.write("(")}formatExpression(state,node.left,node,false);state.write(" "+node.operator+" ");formatExpression(state,node.right,node,true);if(isIn){state.write(")")}},LogicalExpression:BinaryExpression,ConditionalExpression:function ConditionalExpression(node,state){var test=node.test;var precedence=state.expressionsPrecedence[test.type];if(precedence===NEEDS_PARENTHESES||precedence<=state.expressionsPrecedence.ConditionalExpression){state.write("(");this[test.type](test,state);state.write(")")}else{this[test.type](test,state)}state.write(" ? ");this[node.consequent.type](node.consequent,state);state.write(" : ");this[node.alternate.type](node.alternate,state)},NewExpression:function NewExpression(node,state){state.write("new ");var precedence=state.expressionsPrecedence[node.callee.type];if(precedence===NEEDS_PARENTHESES||precedence0){if(this.lineEndSize>0&&(lineEnd.length===1?code[length-1]===lineEnd:code.endsWith(lineEnd))){this.line+=this.lineEndSize;this.column=0}else{this.column+=length}}}},{key:"toString",value:function toString(){return this.output}}]);return State}();function generate(node,options){var state=new State(options);state.generator[node.type](node,state);return state.output}},{}],27:[function(require,module,exports){module.exports=Backoff;function Backoff(opts){opts=opts||{};this.ms=opts.min||100;this.max=opts.max||1e4;this.factor=opts.factor||2;this.jitter=opts.jitter>0&&opts.jitter<=1?opts.jitter:0;this.attempts=0}Backoff.prototype.duration=function(){var ms=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.jitter*ms);ms=(Math.floor(rand*10)&1)==0?ms-deviation:ms+deviation}return Math.min(ms,this.max)|0};Backoff.prototype.reset=function(){this.attempts=0};Backoff.prototype.setMin=function(min){this.ms=min};Backoff.prototype.setMax=function(max){this.max=max};Backoff.prototype.setJitter=function(jitter){this.jitter=jitter}},{}],28:[function(require,module,exports){(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,factory(global["base64-arraybuffer"]={}))})(this,(function(exports){"use strict";var chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";var lookup=typeof Uint8Array==="undefined"?[]:new Uint8Array(256);for(var i=0;i>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[bytes[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};var decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer};exports.decode=decode;exports.encode=encode;Object.defineProperty(exports,"__esModule",{value:true})}))},{}],29:[function(require,module,exports){"use strict";exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var code="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var i=0,len=code.length;i0){throw new Error("Invalid string. Length must be a multiple of 4")}var validLen=b64.indexOf("=");if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen]}function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&255;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&255}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&255;arr[curByte++]=tmp&255}return arr}function tripletToBase64(num){return lookup[num>>18&63]+lookup[num>>12&63]+lookup[num>>6&63]+lookup[num&63]}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength))}if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&63]+"==")}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&63]+lookup[tmp<<2&63]+"=")}return parts.join("")}},{}],30:[function(require,module,exports){},{}],31:[function(require,module,exports){"use strict";var R=typeof Reflect==="object"?Reflect:null;var ReflectApply=R&&typeof R.apply==="function"?R.apply:function ReflectApply(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};var ReflectOwnKeys;if(R&&typeof R.ownKeys==="function"){ReflectOwnKeys=R.ownKeys}else if(Object.getOwnPropertySymbols){ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}}else{ReflectOwnKeys=function ReflectOwnKeys(target){return Object.getOwnPropertyNames(target)}}function ProcessEmitWarning(warning){if(console&&console.warn)console.warn(warning)}var NumberIsNaN=Number.isNaN||function NumberIsNaN(value){return value!==value};function EventEmitter(){EventEmitter.init.call(this)}module.exports=EventEmitter;module.exports.once=once;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._eventsCount=0;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;function checkListener(listener){if(typeof listener!=="function"){throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}}Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||NumberIsNaN(arg)){throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".")}defaultMaxListeners=arg}});EventEmitter.init=function(){if(this._events===undefined||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined};EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||NumberIsNaN(n)){throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n+".")}this._maxListeners=n;return this};function _getMaxListeners(that){if(that._maxListeners===undefined)return EventEmitter.defaultMaxListeners;return that._maxListeners}EventEmitter.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter.prototype.emit=function emit(type){var args=[];for(var i=1;i0)er=args[0];if(er instanceof Error){throw er}var err=new Error("Unhandled error."+(er?" ("+er.message+")":""));err.context=er;throw err}var handler=events[type];if(handler===undefined)return false;if(typeof handler==="function"){ReflectApply(handler,this,args)}else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i0&&existing.length>m&&!existing.warned){existing.warned=true;var w=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners "+"added. Use emitter.setMaxListeners() to "+"increase limit");w.name="MaxListenersExceededWarning";w.emitter=target;w.type=type;w.count=existing.length;ProcessEmitWarning(w)}}return target}EventEmitter.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,false)};EventEmitter.prototype.on=EventEmitter.prototype.addListener;EventEmitter.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,true)};function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=true;if(arguments.length===0)return this.listener.call(this.target);return this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state={fired:false,wrapFn:undefined,target:target,type:type,listener:listener};var wrapped=onceWrapper.bind(state);wrapped.listener=listener;state.wrapFn=wrapped;return wrapped}EventEmitter.prototype.once=function once(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter.prototype.removeListener=function removeListener(type,listener){var list,events,position,i,originalListener;checkListener(listener);events=this._events;if(events===undefined)return this;list=events[type];if(list===undefined)return this;if(list===listener||list.listener===listener){if(--this._eventsCount===0)this._events=Object.create(null);else{delete events[type];if(events.removeListener)this.emit("removeListener",type,list.listener||listener)}}else if(typeof list!=="function"){position=-1;for(i=list.length-1;i>=0;i--){if(list[i]===listener||list[i].listener===listener){originalListener=list[i].listener;position=i;break}}if(position<0)return this;if(position===0)list.shift();else{spliceOne(list,position)}if(list.length===1)events[type]=list[0];if(events.removeListener!==undefined)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(events===undefined)return this;if(events.removeListener===undefined){if(arguments.length===0){this._events=Object.create(null);this._eventsCount=0}else if(events[type]!==undefined){if(--this._eventsCount===0)this._events=Object.create(null);else delete events[type]}return this}if(arguments.length===0){var keys=Object.keys(events);var key;for(i=0;i=0;i--){this.removeListener(type,listeners[i])}}return this};function _listeners(target,type,unwrap){var events=target._events;if(events===undefined)return[];var evlistener=events[type];if(evlistener===undefined)return[];if(typeof evlistener==="function")return unwrap?[evlistener.listener||evlistener]:[evlistener];return unwrap?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}EventEmitter.prototype.listeners=function listeners(type){return _listeners(this,type,true)};EventEmitter.prototype.rawListeners=function rawListeners(type){return _listeners(this,type,false)};EventEmitter.listenerCount=function(emitter,type){if(typeof emitter.listenerCount==="function"){return emitter.listenerCount(type)}else{return listenerCount.call(emitter,type)}};EventEmitter.prototype.listenerCount=listenerCount;function listenerCount(type){var events=this._events;if(events!==undefined){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener!==undefined){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]};function arrayClone(arr,n){var copy=new Array(n);for(var i=0;i * @license MIT */ "use strict";var base64=require("base64-js");var ieee754=require("ieee754");exports.Buffer=Buffer;exports.SlowBuffer=SlowBuffer;exports.INSPECT_MAX_BYTES=50;var K_MAX_LENGTH=2147483647;exports.kMaxLength=K_MAX_LENGTH;Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=="undefined"&&typeof console.error==="function"){console.error("This browser lacks typed array (Uint8Array) support which is required by "+"`buffer` v5.x. Use `buffer` v4.x if you require old browser support.")}function typedArraySupport(){try{var arr=new Uint8Array(1);arr.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}};return arr.foo()===42}catch(e){return false}}Object.defineProperty(Buffer.prototype,"parent",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer}});Object.defineProperty(Buffer.prototype,"offset",{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"')}var buf=new Uint8Array(length);buf.__proto__=Buffer.prototype;return buf}function Buffer(arg,encodingOrOffset,length){if(typeof arg==="number"){if(typeof encodingOrOffset==="string"){throw new TypeError('The "string" argument must be of type string. Received type number')}return allocUnsafe(arg)}return from(arg,encodingOrOffset,length)}if(typeof Symbol!=="undefined"&&Symbol.species!=null&&Buffer[Symbol.species]===Buffer){Object.defineProperty(Buffer,Symbol.species,{value:null,configurable:true,enumerable:false,writable:false})}Buffer.poolSize=8192;function from(value,encodingOrOffset,length){if(typeof value==="string"){return fromString(value,encodingOrOffset)}if(ArrayBuffer.isView(value)){return fromArrayLike(value)}if(value==null){throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length)}if(typeof value==="number"){throw new TypeError('The "value" argument must not be of type number. Received type number')}var valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length)}var b=fromObject(value);if(b)return b;if(typeof Symbol!=="undefined"&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==="function"){return Buffer.from(value[Symbol.toPrimitive]("string"),encodingOrOffset,length)}throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, "+"or Array-like Object. Received type "+typeof value)}Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length)};Buffer.prototype.__proto__=Uint8Array.prototype;Buffer.__proto__=Uint8Array;function assertSize(size){if(typeof size!=="number"){throw new TypeError('"size" argument must be of type number')}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"')}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size)}if(fill!==undefined){return typeof encoding==="string"?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill)}return createBuffer(size)}Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding)};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0)}Buffer.allocUnsafe=function(size){return allocUnsafe(size)};Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size)};function fromString(string,encoding){if(typeof encoding!=="string"||encoding===""){encoding="utf8"}if(!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}var length=byteLength(string,encoding)|0;var buf=createBuffer(length);var actual=buf.write(string,encoding);if(actual!==length){buf=buf.slice(0,actual)}return buf}function fromArrayLike(array){var length=array.length<0?0:checked(array.length)|0;var buf=createBuffer(length);for(var i=0;i=K_MAX_LENGTH){throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+K_MAX_LENGTH.toString(16)+" bytes")}return length|0}function SlowBuffer(length){if(+length!=length){length=0}return Buffer.alloc(+length)}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype};Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array')}if(a===b)return 0;var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;var loweredCase=false;for(;;){switch(encoding){case"ascii":case"latin1":case"binary":return len;case"utf8":case"utf-8":return utf8ToBytes(string).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return len*2;case"hex":return len>>>1;case"base64":return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length}encoding=(""+encoding).toLowerCase();loweredCase=true}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){var loweredCase=false;if(start===undefined||start<0){start=0}if(start>this.length){return""}if(end===undefined||end>this.length){end=this.length}if(end<=0){return""}end>>>=0;start>>>=0;if(end<=start){return""}if(!encoding)encoding="utf8";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"latin1":case"binary":return latin1Slice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}}Buffer.prototype._isBuffer=true;function swap(b,n,m){var i=b[n];b[n]=b[m];b[m]=i}Buffer.prototype.swap16=function swap16(){var len=this.length;if(len%2!==0){throw new RangeError("Buffer size must be a multiple of 16-bits")}for(var i=0;imax)str+=" ... ";return""};Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength)}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+"Received type "+typeof target)}if(start===undefined){start=0}if(end===undefined){end=target?target.length:0}if(thisStart===undefined){thisStart=0}if(thisEnd===undefined){thisEnd=this.length}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError("out of range index")}if(thisStart>=thisEnd&&start>=end){return 0}if(thisStart>=thisEnd){return-1}if(start>=end){return 1}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;var x=thisEnd-thisStart;var y=end-start;var len=Math.min(x,y);var thisCopy=this.slice(thisStart,thisEnd);var targetCopy=target.slice(start,end);for(var i=0;i2147483647){byteOffset=2147483647}else if(byteOffset<-2147483648){byteOffset=-2147483648}byteOffset=+byteOffset;if(numberIsNaN(byteOffset)){byteOffset=dir?0:buffer.length-1}if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1}else if(byteOffset<0){if(dir)byteOffset=0;else return-1}if(typeof val==="string"){val=Buffer.from(val,encoding)}if(Buffer.isBuffer(val)){if(val.length===0){return-1}return arrayIndexOf(buffer,val,byteOffset,encoding,dir)}else if(typeof val==="number"){val=val&255;if(typeof Uint8Array.prototype.indexOf==="function"){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset)}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset)}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir)}throw new TypeError("val must be string, number or Buffer")}function arrayIndexOf(arr,val,byteOffset,encoding,dir){var indexSize=1;var arrLength=arr.length;var valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==="ucs2"||encoding==="ucs-2"||encoding==="utf16le"||encoding==="utf-16le"){if(arr.length<2||val.length<2){return-1}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2}}function read(buf,i){if(indexSize===1){return buf[i]}else{return buf.readUInt16BE(i*indexSize)}}var i;if(dir){var foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){var found=true;for(var j=0;jremaining){length=remaining}}var strLen=string.length;if(length>strLen/2){length=strLen/2}for(var i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding="utf8"}else{encoding=length;length=undefined}}else{throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported")}var remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError("Attempt to write outside buffer bounds")}if(!encoding)encoding="utf8";var loweredCase=false;for(;;){switch(encoding){case"hex":return hexWrite(this,string,offset,length);case"utf8":case"utf-8":return utf8Write(this,string,offset,length);case"ascii":return asciiWrite(this,string,offset,length);case"latin1":case"binary":return latin1Write(this,string,offset,length);case"base64":return base64Write(this,string,offset,length);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(""+encoding).toLowerCase();loweredCase=true}}};Buffer.prototype.toJSON=function toJSON(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);var res=[];var i=start;while(i239?4:firstByte>223?3:firstByte>191?2:1;if(i+bytesPerSequence<=end){var secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<128){codePoint=firstByte}break;case 2:secondByte=buf[i+1];if((secondByte&192)===128){tempCodePoint=(firstByte&31)<<6|secondByte&63;if(tempCodePoint>127){codePoint=tempCodePoint}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&192)===128&&(thirdByte&192)===128){tempCodePoint=(firstByte&15)<<12|(secondByte&63)<<6|thirdByte&63;if(tempCodePoint>2047&&(tempCodePoint<55296||tempCodePoint>57343)){codePoint=tempCodePoint}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&192)===128&&(thirdByte&192)===128&&(fourthByte&192)===128){tempCodePoint=(firstByte&15)<<18|(secondByte&63)<<12|(thirdByte&63)<<6|fourthByte&63;if(tempCodePoint>65535&&tempCodePoint<1114112){codePoint=tempCodePoint}}}}if(codePoint===null){codePoint=65533;bytesPerSequence=1}else if(codePoint>65535){codePoint-=65536;res.push(codePoint>>>10&1023|55296);codePoint=56320|codePoint&1023}res.push(codePoint);i+=bytesPerSequence}return decodeCodePointsArray(res)}var MAX_ARGUMENTS_LENGTH=4096;function decodeCodePointsArray(codePoints){var len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints)}var res="";var i=0;while(ilen)end=len;var out="";for(var i=start;ilen){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(endlength)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length)}var val=this[offset+--byteLength];var mul=1;while(byteLength>0&&(mul*=256)){val+=this[offset+--byteLength]*mul}return val};Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readIntLE=function readIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var val=this[offset];var mul=1;var i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);var i=byteLength;var mul=1;var val=this[offset+--i];while(i>0&&(mul*=256)){val+=this[offset+--i]*mul}mul*=128;if(val>=mul)val-=Math.pow(2,8*byteLength);return val};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function readFloatLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError("Index out of range")}Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var mul=1;var i=0;this[offset]=value&255;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){var maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0)}var i=byteLength-1;var mul=1;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){this[offset+i]=value/mul&255}return offset+byteLength};Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);this[offset]=value&255;return offset+1};Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&255;return offset+4};Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=0;var mul=1;var sub=0;this[offset]=value&255;while(++i>0)-sub&255}return offset+byteLength};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){var limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit)}var i=byteLength-1;var mul=1;var sub=0;this[offset+i]=value&255;while(--i>=0&&(mul*=256)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1}this[offset+i]=(value/mul>>0)-sub&255}return offset+byteLength};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(value<0)value=255+value+1;this[offset]=value&255;return offset+1};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value&255;this[offset+1]=value>>>8;return offset+2};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);this[offset]=value>>>8;this[offset+1]=value&255;return offset+2};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);this[offset]=value&255;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&255;return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError("Index out of range");if(offset<0)throw new RangeError("Index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,34028234663852886e22,-34028234663852886e22)}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,17976931348623157e292,-17976931348623157e292)}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError("argument should be a Buffer");if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError("Index out of range");if(end<0)throw new RangeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-targetStart=0;--i){target[i+targetStart]=this[i+start]}}else{Uint8Array.prototype.set.call(target,this.subarray(start,end),targetStart)}return len};Buffer.prototype.fill=function fill(val,start,end,encoding){if(typeof val==="string"){if(typeof start==="string"){encoding=start;start=0;end=this.length}else if(typeof end==="string"){encoding=end;end=this.length}if(encoding!==undefined&&typeof encoding!=="string"){throw new TypeError("encoding must be a string")}if(typeof encoding==="string"&&!Buffer.isEncoding(encoding)){throw new TypeError("Unknown encoding: "+encoding)}if(val.length===1){var code=val.charCodeAt(0);if(encoding==="utf8"&&code<128||encoding==="latin1"){val=code}}}else if(typeof val==="number"){val=val&255}if(start<0||this.length>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;var i;if(typeof val==="number"){for(i=start;i55295&&codePoint<57344){if(!leadSurrogate){if(codePoint>56319){if((units-=3)>-1)bytes.push(239,191,189);continue}else if(i+1===length){if((units-=3)>-1)bytes.push(239,191,189);continue}leadSurrogate=codePoint;continue}if(codePoint<56320){if((units-=3)>-1)bytes.push(239,191,189);leadSurrogate=codePoint;continue}codePoint=(leadSurrogate-55296<<10|codePoint-56320)+65536}else if(leadSurrogate){if((units-=3)>-1)bytes.push(239,191,189)}leadSurrogate=null;if(codePoint<128){if((units-=1)<0)break;bytes.push(codePoint)}else if(codePoint<2048){if((units-=2)<0)break;bytes.push(codePoint>>6|192,codePoint&63|128)}else if(codePoint<65536){if((units-=3)<0)break;bytes.push(codePoint>>12|224,codePoint>>6&63|128,codePoint&63|128)}else if(codePoint<1114112){if((units-=4)<0)break;bytes.push(codePoint>>18|240,codePoint>>12&63|128,codePoint>>6&63|128,codePoint&63|128)}else{throw new Error("Invalid code point")}}return bytes}function asciiToBytes(str){var byteArray=[];for(var i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(base64clean(str))}function blitBuffer(src,dst,offset,length){for(var i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name}function numberIsNaN(obj){return obj!==obj}}).call(this)}).call(this,require("buffer").Buffer)},{"base64-js":29,buffer:32,ieee754:114}],33:[function(require,module,exports){"use strict";var GetIntrinsic=require("get-intrinsic");var callBind=require("./");var $indexOf=callBind(GetIntrinsic("String.prototype.indexOf"));module.exports=function callBoundIntrinsic(name,allowMissing){var intrinsic=GetIntrinsic(name,!!allowMissing);if(typeof intrinsic==="function"&&$indexOf(name,".prototype.")>-1){return callBind(intrinsic)}return intrinsic}},{"./":34,"get-intrinsic":83}],34:[function(require,module,exports){"use strict";var bind=require("function-bind");var GetIntrinsic=require("get-intrinsic");var $apply=GetIntrinsic("%Function.prototype.apply%");var $call=GetIntrinsic("%Function.prototype.call%");var $reflectApply=GetIntrinsic("%Reflect.apply%",true)||bind.call($call,$apply);var $gOPD=GetIntrinsic("%Object.getOwnPropertyDescriptor%",true);var $defineProperty=GetIntrinsic("%Object.defineProperty%",true);var $max=GetIntrinsic("%Math.max%");if($defineProperty){try{$defineProperty({},"a",{value:1})}catch(e){$defineProperty=null}}module.exports=function callBind(originalFunction){var func=$reflectApply(bind,$call,arguments);if($gOPD&&$defineProperty){var desc=$gOPD(func,"length");if(desc.configurable){$defineProperty(func,"length",{value:1+$max(0,originalFunction.length-(arguments.length-1))})}}return func};var applyBind=function applyBind(){return $reflectApply(bind,$apply,arguments)};if($defineProperty){$defineProperty(module.exports,"apply",{value:applyBind})}else{module.exports.apply=applyBind}},{"function-bind":81,"get-intrinsic":83}],35:[function(require,module,exports){var EventEmitter=require("events").EventEmitter;var storage=require("./lib/storage");var logger=require("./lib/logger");var debug=require("./lib/debug");var copy=require("./lib/copy");var help=require("./lib/help");var perf=require("./lib/perf");var log=require("./lib/log");var getAllRoutes=require("wayfarer/get-all-routes");module.exports=expose;function expose(opts){opts=opts||{};store.storeName="choo-devtools";return store;function store(state,emitter,app){var localEmitter=new EventEmitter;if(typeof window!=="undefined"){logger(state,emitter,opts)}emitter.on("DOMContentLoaded",(function(){if(typeof window==="undefined")return;window.choo={};window.choo.state=state;window.choo.emit=function(){emitter.emit.apply(emitter,arguments)};window.choo.on=function(eventName,listener){emitter.on(eventName,listener)};debug(state,emitter,app,localEmitter);log(state,emitter,app,localEmitter);perf(state,emitter,app,localEmitter);window.choo.copy=copy;if(app.router&&app.router.router){window.choo.routes=Object.keys(getAllRoutes(app.router.router))}storage();help()}))}}},{"./lib/copy":36,"./lib/debug":37,"./lib/help":38,"./lib/log":39,"./lib/logger":40,"./lib/perf":41,"./lib/storage":42,events:31,"wayfarer/get-all-routes":238}],36:[function(require,module,exports){var stateCopy=require("state-copy");var pluck=require("plucker");module.exports=copy;function copy(state){var isStateString=state&&typeof state==="string";var isChooPath=isStateString&&arguments.length===1&&state.indexOf("state.")===0;if(!state||typeof state==="function")state=window.choo.state;if(isChooPath)[].push.call(arguments,{state:window.choo.state});stateCopy(isStateString?pluck.apply(this,arguments):state)}},{plucker:172,"state-copy":230}],37:[function(require,module,exports){var onChange=require("object-change-callsite");var nanologger=require("nanologger");var assert=require("assert");var enabledMessage="Debugging enabled. To disable run: `choo.debug = false`";var disabledMessage="Debugging disabled. We hope it was helpful! 🙌";module.exports=debug;function debug(state,emitter,app,localEmitter){var log=nanologger("choo-devtools");var enabled=window.localStorage.logLevel==="debug";if(enabled)log.info(enabledMessage);state=onChange(state,(function(attr,value,callsite){if(!enabled)return;callsite=callsite.split("\n")[1].replace(/^ +/,"");log.info("state."+attr,value,"\n"+callsite)}));app.state=state;Object.defineProperty(window.choo,"debug",{get:function(){window.localStorage.logLevel="debug";localEmitter.emit("debug",true);enabled=true;return enabledMessage},set:function(bool){assert.equal(typeof bool,"boolean","choo-devtools.debug: bool should be type boolean");window.localStorage.logLevel=bool?"debug":"info";enabled=bool;localEmitter.emit("debug",enabled);if(enabled)log.info(enabledMessage);else log.info(disabledMessage)}})}},{assert:19,nanologger:154,"object-change-callsite":165}],38:[function(require,module,exports){module.exports=help;function help(){Object.defineProperty(window.choo,"help",{get:get,set:noop});function get(){setTimeout((function(){print("copy","Serialize the current state to the clipboard.");print("debug","Enable Choo debug mode.");print("emit","Emit an event in the Choo emitter.");print("help","Print usage information.");print("log","Print the last 150 events emitted.");print("on","Listen for an event in the Choo emitter.");print("once","Listen for an event once in the Choo emitter.");print("perf","Print out performance metrics");print("state","Print the Choo state object.");print("storage","Print browser storage information.")}),0);return"Choo command overview"}}function print(cmd,desc){var color="#cc99cc";console.log(" %cchoo."+cmd,"color: "+color,"— "+desc)}function noop(){}},{}],39:[function(require,module,exports){var removeItems=require("remove-array-items");var scheduler=require("nanoscheduler")();var nanologger=require("nanologger");var _log=nanologger("choo");var clone=require("clone");var MAX_HISTORY_LENGTH=150;module.exports=log;function log(state,emitter,app,localEmitter){var shouldDebug=window.localStorage.logLevel==="debug";var history=[];var i=0;var shouldWarn=true;localEmitter.on("debug",(function(bool){shouldDebug=bool}));window.choo._history=history;window.choo.history=showHistory;Object.defineProperty(window.choo,"log",{get:showHistory,set:noop});Object.defineProperty(window.choo,"history",{get:showHistory,set:noop});emitter.on("*",(function(name,data){i+=1;var entry=new Event(name,data,state);history.push(entry);scheduler.push((function(){var length=history.length;if(length>MAX_HISTORY_LENGTH){removeItems(history,0,length-MAX_HISTORY_LENGTH)}}))}));function showHistory(){setTimeout((function(){console.table(history)}),0);var events=i===1?"event":"events";var msg=i+" "+events+" recorded, showing the last "+MAX_HISTORY_LENGTH+".";if(shouldDebug===false){msg+=" Enable state capture by calling `choo.debug`."}else{msg+=" Disable state capture by calling `choo.debug = false`."}return msg}function Event(name,data,state){this.name=name;this.data=data===undefined?"":data;this.state=shouldDebug?tryClone(state):""}function tryClone(state){try{var _state=clone(state);if(!shouldWarn)shouldWarn=true;return _state}catch(ex){if(shouldWarn){_log.warn("Could not clone your app state. Make sure to have a serializable state so it can be cloned");shouldWarn=false}return""}}}function noop(){}},{clone:51,nanologger:154,nanoscheduler:162,"remove-array-items":43}],40:[function(require,module,exports){var scheduler=require("nanoscheduler")();var nanologger=require("nanologger");var Hooks=require("choo-hooks");module.exports=logger;function logger(state,emitter,opts){var initialRender=true;var hooks=Hooks(emitter);var log=nanologger("choo");hooks.on("log:debug",logger("debug"));hooks.on("log:info",logger("info"));hooks.on("log:warn",logger("warn"));hooks.on("log:error",logger("error"));hooks.on("log:fatal",logger("fatal"));hooks.on("event",(function(eventName,data,timing){if(opts.filter&&!opts.filter(eventName,data,timing))return;if(timing){var duration=timing.duration.toFixed();var level=duration<50?"info":"warn";if(data!==undefined)logger(level)(eventName,data,duration+"ms");else logger(level)(eventName,duration+"ms")}else{if(data!==undefined)logger("info")(eventName,data);else logger("info")(eventName)}}));hooks.on("unhandled",(function(eventName,data){logger("error")("No listeners for "+eventName)}));hooks.on("DOMContentLoaded",(function(timing){if(!timing)return logger("info")("DOMContentLoaded");var level=timing.interactive<1e3?"info":"warn";logger(level)("DOMContentLoaded",timing.interactive+"ms to interactive")}));hooks.on("render",(function(timings){if(!timings||!timings.render)return logger("info")("render");var duration=timings.render.duration.toFixed();var msg="render";if(initialRender){initialRender=false;msg="initial "+msg}var fps=Math.min((600/duration).toFixed(),60);if(fps===60){logger("info")(msg,fps+"fps",duration+"ms")}else{var times={render:timings.render.duration.toFixed()+"ms"};if(timings.morph)times.morph=timings.morph.duration.toFixed()+"ms";logger("warn")(msg,fps+"fps",duration+"ms",times)}}));hooks.on("resource-timing-buffer-full",(function(){logger("error")("The browser's Resource Resource timing buffer is full. Cannot store any more timing information")}));hooks.start();function logger(level){return function(){var args=[];for(var i=0,len=arguments.length;imaxTime)maxTime=totalTime;var median=getMedian(stat.entries);if(median>maxMedian)maxMedian=median;var name=self.rename(stat.name);return new PerfEntry(name,totalTime,median,stat.count)}));var barLength=10;fmt.forEach((function(entry){var totalTime=entry["Total Time (ms)"];var median=entry["Median (ms)"];entry[" "]=createBar(totalTime/maxTime*100/barLength);entry[" "]=createBar(median/maxMedian*100/barLength)}));function createBar(len){var str="";for(var i=0,max=Math.round(len);i=length||removeCount<=0||startIdx<0){return}removeCount=startIdx+removeCount>length?length-startIdx:removeCount;var len=length-removeCount;for(i=startIdx;i is not the same type as the new node <"+newTree.nodeName.toLowerCase()+">.");var morphTiming=nanotiming("choo.morph");nanomorph(self._tree,newTree);morphTiming();renderTiming()})));documentReady((function(){self.emitter.emit(self._events.DOMCONTENTLOADED);self._loaded=true}));startTiming();return this._tree};Choo.prototype.mount=function mount(selector){var mountTiming=nanotiming("choo.mount('"+selector+"')");if(typeof window!=="object"){assert.ok(typeof selector==="string","choo.mount: selector should be type String");this.selector=selector;mountTiming();return this}assert.ok(typeof selector==="string"||typeof selector==="object","choo.mount: selector should be type String or HTMLElement");var self=this;documentReady((function(){var renderTiming=nanotiming("choo.render");var newTree=self.start();if(typeof selector==="string"){self._tree=document.querySelector(selector)}else{self._tree=selector}assert.ok(self._tree,"choo.mount: could not query selector: "+selector);assert.equal(self._tree.nodeName,newTree.nodeName,"choo.mount: The target node <"+self._tree.nodeName.toLowerCase()+"> is not the same type as the new node <"+newTree.nodeName.toLowerCase()+">.");var morphTiming=nanotiming("choo.morph");nanomorph(self._tree,newTree);morphTiming();renderTiming()}));mountTiming()};Choo.prototype.toString=function(location,state){state=state||{};state.components=state.components||{};state.events=Object.assign({},state.events,this._events);assert.notEqual(typeof window,"object","choo.mount: window was found. .toString() must be called in Node, use .start() or .mount() if running in the browser");assert.equal(typeof location,"string","choo.toString: location should be type string");assert.equal(typeof state,"object","choo.toString: state should be type object");this._setCache(state);this._matchRoute(state,location);this.emitter.removeAllListeners();this._stores.forEach((function(initStore){initStore(state)}));var html=this._prerender(state);assert.ok(html,"choo.toString: no valid value returned for the route "+location);assert(!Array.isArray(html),"choo.toString: return value was an array for the route "+location);return typeof html.outerHTML==="string"?html.outerHTML:html.toString()};Choo.prototype._matchRoute=function(state,locationOverride){var location,queryString;if(locationOverride){location=locationOverride.replace(/\?.+$/,"").replace(/\/$/,"");if(!this._hashEnabled)location=location.replace(/#.+$/,"");queryString=locationOverride}else{location=window.location.pathname.replace(/\/$/,"");if(this._hashEnabled)location+=window.location.hash.replace(/^#/,"/");queryString=window.location.search}var matched=this.router.match(location);this._handler=matched.cb;state.href=location;state.query=nanoquery(queryString);state.route=matched.route;state.params=matched.params};Choo.prototype._prerender=function(state){var routeTiming=nanotiming("choo.prerender('"+state.route+"')");var res=this._handler(state,this.emit);routeTiming();return res};Choo.prototype._setCache=function(state){var cache=new Cache(state,this.emitter.emit.bind(this.emitter),this._cache);state.cache=renderComponent;function renderComponent(Component,id){assert.equal(typeof Component,"function","choo.state.cache: Component should be type function");var args=[];for(var i=0,len=arguments.length;i */ module.exports=clipboardCopy;function clipboardCopy(text){if(navigator.clipboard){return navigator.clipboard.writeText(text).catch((function(err){throw err!==undefined?err:new DOMException("The request is not allowed","NotAllowedError")}))}var span=document.createElement("span");span.textContent=text;span.style.whiteSpace="pre";span.style.webkitUserSelect="auto";span.style.userSelect="all";document.body.appendChild(span);var selection=window.getSelection();var range=window.document.createRange();selection.removeAllRanges();range.selectNode(span);selection.addRange(range);var success=false;try{success=window.document.execCommand("copy")}catch(err){console.log("error",err)}selection.removeAllRanges();window.document.body.removeChild(span);return success?Promise.resolve():Promise.reject(new DOMException("The request is not allowed","NotAllowedError"))}},{}],51:[function(require,module,exports){(function(Buffer){(function(){var clone=function(){"use strict";function _instanceof(obj,type){return type!=null&&obj instanceof type}var nativeMap;try{nativeMap=Map}catch(_){nativeMap=function(){}}var nativeSet;try{nativeSet=Set}catch(_){nativeSet=function(){}}var nativePromise;try{nativePromise=Promise}catch(_){nativePromise=function(){}}function clone(parent,circular,depth,prototype,includeNonEnumerable){if(typeof circular==="object"){depth=circular.depth;prototype=circular.prototype;includeNonEnumerable=circular.includeNonEnumerable;circular=circular.circular}var allParents=[];var allChildren=[];var useBuffer=typeof Buffer!="undefined";if(typeof circular=="undefined")circular=true;if(typeof depth=="undefined")depth=Infinity;function _clone(parent,depth){if(parent===null)return null;if(depth===0)return parent;var child;var proto;if(typeof parent!="object"){return parent}if(_instanceof(parent,nativeMap)){child=new nativeMap}else if(_instanceof(parent,nativeSet)){child=new nativeSet}else if(_instanceof(parent,nativePromise)){child=new nativePromise((function(resolve,reject){parent.then((function(value){resolve(_clone(value,depth-1))}),(function(err){reject(_clone(err,depth-1))}))}))}else if(clone.__isArray(parent)){child=[]}else if(clone.__isRegExp(parent)){child=new RegExp(parent.source,__getRegExpFlags(parent));if(parent.lastIndex)child.lastIndex=parent.lastIndex}else if(clone.__isDate(parent)){child=new Date(parent.getTime())}else if(useBuffer&&Buffer.isBuffer(parent)){if(Buffer.allocUnsafe){child=Buffer.allocUnsafe(parent.length)}else{child=new Buffer(parent.length)}parent.copy(child);return child}else if(_instanceof(parent,Error)){child=Object.create(parent)}else{if(typeof prototype=="undefined"){proto=Object.getPrototypeOf(parent);child=Object.create(proto)}else{child=Object.create(prototype);proto=prototype}}if(circular){var index=allParents.indexOf(parent);if(index!=-1){return allChildren[index]}allParents.push(parent);allChildren.push(child)}if(_instanceof(parent,nativeMap)){parent.forEach((function(value,key){var keyChild=_clone(key,depth-1);var valueChild=_clone(value,depth-1);child.set(keyChild,valueChild)}))}if(_instanceof(parent,nativeSet)){parent.forEach((function(value){var entryChild=_clone(value,depth-1);child.add(entryChild)}))}for(var i in parent){var attrs;if(proto){attrs=Object.getOwnPropertyDescriptor(proto,i)}if(attrs&&attrs.set==null){continue}child[i]=_clone(parent[i],depth-1)}if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(parent);for(var i=0;i=d||(f.line>=d&&(f=l(d,0)),d=g.line,null==b?this.uncomment(g,f,c)?b="un":(this.lineComment(g,f,c),b="line"):"un"==b?this.uncomment(g,f,c):this.lineComment(g,f,c))}}));r.defineExtension("lineComment",(function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=b.getLine(c.line);if(null!=g&&!J(b,c,g)){var f=a.lineComment||e.lineComment;if(f){var m=Math.min(0!=d.ch||d.line==c.line?d.line+1:d.line,b.lastLine()+1),u=null==a.padding?" ":a.padding,k=a.commentBlankLines||c.line==d.line;b.operation((function(){if(a.indent){for(var p=null,h=c.line;hq.length)p=q}for(h=c.line;hm||b.operation((function(){if(0!=a.fullLines){var k=w.test(b.getLine(m));b.replaceRange(u+f,l(m));b.replaceRange(g+u,l(c.line,0));var p=a.blockCommentLead||e.blockCommentLead;if(null!=p)for(var h=c.line+1;h<=m;++h)(h!=m||k)&&b.replaceRange(p+u,l(h,0))}else k=0==K(b.getCursor("to"),d),p=!b.somethingSelected(),b.replaceRange(f,d),k&&b.setSelection(p?d:b.getCursor("from"),d),b.replaceRange(g,c)}))}}));r.defineExtension("uncomment",(function(c,d,a){a||(a=E);var b=this,e=G(b,c),g=Math.min(0!=d.ch||d.line==c.line?d.line:d.line-1,b.lastLine()),f=Math.min(c.line,g),m=a.lineComment||e.lineComment,u=[],k=null==a.padding?" ":a.padding,p;a:if(m){for(var h=f;h<=g;++h){var q=b.getLine(h),t=q.indexOf(m);-1x||(A.slice(v,v+k.length)==k&&(v+=k.length),p=!0,b.replaceRange("",l(n,x),l(n,v)))}}));if(p)return!0}var y=a.blockCommentStart||e.blockCommentStart,z=a.blockCommentEnd||e.blockCommentEnd;if(!y||!z)return!1;var H=a.blockCommentLead||e.blockCommentLead,C=b.getLine(f),D=C.indexOf(y);if(-1==D)return!1;var F=g==f?C:b.getLine(g),B=F.indexOf(z,g==f?D+y.length:0);a=l(f,D+1);e=l(g,B+1);if(-1==B||!/comment/.test(b.getTokenTypeAt(a))||!/comment/.test(b.getTokenTypeAt(e))||-1c.ch&&(d.end=c.ch,d.string=d.string.slice(0,c.ch-d.start)):d={start:c.ch,end:c.ch,string:"",state:d.state,type:"."==d.string?"property":null};for(g=d;"property"==g.type;){g=l(a,r(c.line,g.start));if("."!=g.string)return;g=l(a,r(c.line,g.start));if(!p)var p=[];p.push(g)}return{list:u(d,p,b,e),from:r(c.line,d.start),to:r(c.line,d.end)}}}}function v(a,b){a=a.getTokenAt(b);b.ch==a.start+1&&"."==a.string.charAt(0)?(a.end=a.start,a.string=".",a.type="property"):/^\.[\w$_]*$/.test(a.string)&&(a.type="property",a.start++,a.string=a.string.replace(/\./,""));return a}function u(a,b,l,e){function c(h){var k;if(k=0==h.lastIndexOf(p,0)){a:if(Array.prototype.indexOf)k=-1!=g.indexOf(h);else{for(k=g.length;k--;)if(g[k]===h){k=!0;break a}k=!1}k=!k}k&&g.push(h)}function d(h){"string"==typeof h?q(w,c):h instanceof Array?q(x,c):h instanceof Function&&q(y,c);if(Object.getOwnPropertyNames&&Object.getPrototypeOf)for(;h;h=Object.getPrototypeOf(h))Object.getOwnPropertyNames(h).forEach(c);else for(var k in h)c(k)}var g=[],p=a.string,n=e&&e.globalScope||window;if(b&&b.length){a=b.pop();var f;a.type&&0===a.type.indexOf("variable")?(e&&e.additionalContext&&(f=e.additionalContext[a.string]),e&&!1===e.useGlobalScope||(f=f||n[a.string])):"string"==a.type?f="":"atom"==a.type?f=1:"function"==a.type&&(null==n.jQuery||"$"!=a.string&&"jQuery"!=a.string||"function"!=typeof n.jQuery?null!=n._&&"_"==a.string&&"function"==typeof n._&&(f=n._()):f=n.jQuery());for(;null!=f&&b.length;)f=f[b.pop().string];null!=f&&d(f)}else{for(b=a.state.localVars;b;b=b.next)c(b.name);for(f=a.state.context;f;f=f.prev)for(b=f.vars;b;b=b.next)c(b.name);for(b=a.state.globalVars;b;b=b.next)c(b.name);if(e&&null!=e.additionalContext)for(var z in e.additionalContext)c(z);e&&!1===e.useGlobalScope||d(n);q(l,c)}return g}var r=m.Pos;m.registerHelper("hint","javascript",(function(a,b){return t(a,A,(function(l,e){return l.getTokenAt(e)}),b)}));m.registerHelper("hint","coffeescript",(function(a,b){return t(a,B,v,b)}));var w="charAt charCodeAt indexOf lastIndexOf substring substr slice trim trimLeft trimRight toUpperCase toLowerCase split concat match replace search".split(" "),x="length concat join splice push pop shift unshift slice reverse sort indexOf lastIndexOf every some filter forEach map reduce reduceRight ".split(" "),y=["prototype","apply","call","bind"],A="break case catch class const continue debugger default delete do else export extends false finally for function if in import instanceof new null return super switch this throw true try typeof var void while with yield".split(" "),B="and break catch class continue delete do else extends false finally for if in instanceof isnt new no not null of off on or return switch then throw true try typeof until void while with yes".split(" ")}))},{"../../lib/codemirror":56}],54:[function(require,module,exports){(function(h){"object"==typeof exports&&"object"==typeof module?h(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],h):h(CodeMirror)})((function(h){function B(a,b){this.cm=a;this.options=b;this.widget=null;this.tick=this.debounce=0;this.startPos=this.cm.getCursor("start");this.startLen=this.cm.getLine(this.startPos.line).length-this.cm.getSelection().length;if(this.options.updateOnCursorActivity){var c=this;a.on("cursorActivity",this.activityFunc=function(){c.cursorActivity()})}}function J(a,b){function c(r,g){var m="string"!=typeof g?function(k){return g(k,b)}:d.hasOwnProperty(g)?d[g]:g;p[r]=m}var d={Up:function(){b.moveFocus(-1)},Down:function(){b.moveFocus(1)},PageUp:function(){b.moveFocus(-b.menuSize()+1,!0)},PageDown:function(){b.moveFocus(b.menuSize()-1,!0)},Home:function(){b.setFocus(0)},End:function(){b.setFocus(b.length-1)},Enter:b.pick,Tab:b.pick,Esc:b.close};/Mac/.test(navigator.platform)&&(d["Ctrl-P"]=function(){b.moveFocus(-1)},d["Ctrl-N"]=function(){b.moveFocus(1)});var e=a.options.customKeys,p=e?{}:d;if(e)for(var f in e)e.hasOwnProperty(f)&&c(f,e[f]);if(a=a.options.extraKeys)for(f in a)a.hasOwnProperty(f)&&c(f,a[f]);return p}function C(a,b){for(;b&&b!=a;){if("LI"===b.nodeName.toUpperCase()&&b.parentNode==a)return b;b=b.parentNode}}function D(a,b){this.id="cm-complete-"+Math.floor(Math.random(1e6));this.completion=a;this.data=b;this.picked=!1;var c=this,d=a.cm,e=d.getInputField().ownerDocument,p=e.defaultView||e.parentWindow,f=this.hints=e.createElement("ul");f.setAttribute("role","listbox");f.setAttribute("aria-expanded","true");f.id=this.id;f.className="CodeMirror-hints "+a.cm.options.theme;this.selectedHint=b.selectedHint||0;for(var r=b.list,g=0;gf.clientHeight+1:!1;var u;setTimeout((function(){u=d.getScrollInfo()}));if(0y&&(f.style.height=y-5+"px",f.style.top=(w=g.bottom-l.top-q)+"px",q=d.getCursor(),b.from.ch!=q.ch&&(g=d.cursorCoords(q),f.style.left=(v=g.left-m)+"px",l=f.getBoundingClientRect()))}q=l.right-k;t&&(q+=d.display.nativeBarWidth);0k&&(f.style.width=k-5+"px",q-=l.right-l.left-k),f.style.left=(v=g.left-q-m)+"px");if(t)for(g=f.firstChild;g;g=g.nextSibling)g.style.paddingRight=d.display.nativeBarWidth+"px";d.addKeyMap(this.keyMap=J(a,{moveFocus:function(n,x){c.changeActive(c.selectedHint+n,x)},setFocus:function(n){c.changeActive(n)},menuSize:function(){return c.screenAmount()},length:r.length,close:function(){a.close()},pick:function(){c.pick()},data:b}));if(a.options.closeOnUnfocus){var F;d.on("blur",this.onBlur=function(){F=setTimeout((function(){a.close()}),100)});d.on("focus",this.onFocus=function(){clearTimeout(F)})}d.on("scroll",this.onScroll=function(){var n=d.getScrollInfo(),x=d.getWrapperElement().getBoundingClientRect();u||(u=d.getScrollInfo());var G=w+u.top-n.top,A=G-(p.pageYOffset||(e.documentElement||e.body).scrollTop);E||(A+=f.offsetHeight);if(A<=x.top||A>=x.bottom)return a.close();f.style.top=G+"px";f.style.left=v+u.left-n.left+"px"});h.on(f,"dblclick",(function(n){(n=C(f,n.target||n.srcElement))&&null!=n.hintId&&(c.changeActive(n.hintId),c.pick())}));h.on(f,"click",(function(n){(n=C(f,n.target||n.srcElement))&&null!=n.hintId&&(c.changeActive(n.hintId),a.options.completeOnSingleClick&&c.pick())}));h.on(f,"mousedown",(function(){setTimeout((function(){d.focus()}),20)}));g=this.getSelectedHintRange();0===g.from&&0===g.to||this.scrollToActive();h.signal(b,"select",r[this.selectedHint],f.childNodes[this.selectedHint]);return!0}function K(a,b){if(!a.somethingSelected())return b;a=[];for(var c=0;c=this.data.list.length?a=b?this.data.list.length-1:0:0>a&&(a=b?0:this.data.list.length-1);if(this.selectedHint!=a){if(b=this.hints.childNodes[this.selectedHint])b.className=b.className.replace(" CodeMirror-hint-active",""),b.removeAttribute("aria-selected");b=this.hints.childNodes[this.selectedHint=a];b.className+=" CodeMirror-hint-active";b.setAttribute("aria-selected","true");this.completion.cm.getInputField().setAttribute("aria-activedescendant",b.id);this.scrollToActive();h.signal(this.data,"select",this.data.list[this.selectedHint],b)}},scrollToActive:function(){var a=this.getSelectedHintRange(),b=this.hints.childNodes[a.from];a=this.hints.childNodes[a.to];var c=this.hints.firstChild;b.offsetTopthis.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=a.offsetTop+a.offsetHeight-this.hints.clientHeight+c.offsetTop)},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1},getSelectedHintRange:function(){var a=this.completion.options.scrollMargin||0;return{from:Math.max(0,this.selectedHint-a),to:Math.min(this.data.list.length-1,this.selectedHint+a)}}};h.registerHelper("hint","auto",{resolve:function(a,b){var c=a.getHelpers(b,"hint"),d;return c.length?(a=function(e,p,f){function r(m){if(m==g.length)return p(null);H(g[m],e,f,(function(k){k&&0,]/,closeOnPick:!0,closeOnUnfocus:!0,updateOnCursorActivity:!0,completeOnSingleClick:!0,container:null,customKeys:null,extraKeys:null,paddingForScrollbar:!0,moveOnOverlap:!0};h.defineOption("hintOptions",null)}))},{"../../lib/codemirror":56}],55:[function(require,module,exports){(function(global){(function(){var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,d,c){a instanceof String&&(a=String(a));for(var e=a.length,f=0;f>>0,$jscomp.propertyToPolyfillSymbol[f]=$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(f):$jscomp.POLYFILL_PREFIX+c+"$"+f),$jscomp.defineProperty(e,$jscomp.propertyToPolyfillSymbol[f],{configurable:!0,writable:!0,value:d})))};$jscomp.polyfill("Array.prototype.find",(function(a){return a?a:function(d,c){return $jscomp.findInternal(this,d,c).v}}),"es6","es3");(function(a){"object"==typeof exports&&"object"==typeof module?a(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],a):a(CodeMirror)})((function(a){function d(b){b.state.markedSelection&&b.operation((function(){r(b)}))}function c(b){b.state.markedSelection&&b.state.markedSelection.length&&b.operation((function(){f(b)}))}function e(b,g,h,k){if(0!=p(g,h))for(var l=b.state.markedSelection,n=b.state.markedSelectionStyle,q=g.line;;){var t=q==g.line?g:v(q,0);q+=u;var w=q>=h.line,x=w?h:v(q,0);t=b.markText(t,x,{className:n});null==k?l.push(t):l.splice(k++,0,t);if(w)break}}function f(b){b=b.state.markedSelection;for(var g=0;g=p(h,l.from))return m(b);for(;0p(g,l.from)&&(l.to.line-g.linep(h,n.to);)k.pop().clear(),n=k[k.length-1].find();0>>0,$jscomp.propertyToPolyfillSymbol[M]=$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(M):$jscomp.POLYFILL_PREFIX+D+"$"+M),$jscomp.defineProperty(v,$jscomp.propertyToPolyfillSymbol[M],{configurable:!0,writable:!0,value:E})))};$jscomp.polyfill("Array.prototype.find",(function(y){return y?y:function(E,D){return $jscomp.findInternal(this,E,D).v}}),"es6","es3");(function(y,E){"object"===typeof exports&&"undefined"!==typeof module?module.exports=E():"function"===typeof define&&define.amd?define(E):(y=y||self,y.CodeMirror=E())})(this,(function(){function y(a){return new RegExp("(^|\\s)"+a+"(?:$|\\s)\\s*")}function E(a){for(var b=a.childNodes.length;0f||f>=b)return e+(b-c);e+=f-c;e+=d-e%d;c=f+1}}function ea(a,b){for(var d=0;d=b)return c+Math.min(g,b-e);e+=f-c;e+=d-e%d;c=f+1;if(e>=b)return c}}function hd(a){for(;tc.length<=a;)tc.push(J(tc)+" ");return tc[a]}function J(a){return a[a.length-1]}function uc(a,b){for(var d=[],c=0;cd?0d?-1:1;;){if(b==d)return b;var e=(b+d)/2;e=0>c?Math.ceil(e):Math.floor(e);if(e==b)return a(e)?b:d;a(e)?d=e:b=e+c}}function zg(a,b,d,c){if(!a)return c(b,d,"ltr",0);for(var e=!1,f=0;fb||b==d&&g.to==b)c(Math.max(g.from,b),Math.min(g.to,d),1==g.level?"rtl":"ltr",f),e=!0}e||c(b,d,"ltr")}function Ib(a,b,d){var c;Jb=null;for(var e=0;eb)return e;f.to==b&&(f.from!=f.to&&"before"==d?c=e:Jb=e);f.from==b&&(f.from!=f.to&&"before"!=d?c=e:Jb=e)}return null!=c?c:Jb}function Ia(a,b){var d=a.order;null==d&&(d=a.order=Ag(a.text,b));return d}function sa(a,b,d){if(a.removeEventListener)a.removeEventListener(b,d,!1);else if(a.detachEvent)a.detachEvent("on"+b,d);else{var c=(a=a._handlers)&&a[b];c&&(d=ea(c,d),-1b||b>=a.size)throw Error("There is no line "+(b+a.first)+" in the document.");for(;!a.lines;)for(var d=0;;++d){var c=a.children[d],e=c.chunkSize();if(b=a.first&&bB(a,b)?b:a}function zc(a,b){return 0>B(a,b)?a:b}function C(a,b){if(b.lined)return t(d,w(a,d).text.length);a=w(a,b.line).text.length;d=b.ch;b=null==d||d>a?t(b.line,a):0>d?t(b.line,0):b;return b}function we(a,b){for(var d=[],c=0;cp&&e.splice(m,1,p,e[m+1],u);m+=2;n=Math.min(p,u)}if(q)if(l.opaque)e.splice(r,m-r,p,"overlay "+q),m=r+2;else for(;ra.options.maxHighlightLength&&Ya(a.doc.mode,c.state),f=xe(a,b,c);e&&(c.state=e);b.stateAfter=c.save(!e);b.styles=f.styles;f.classes?b.styleClasses=f.classes:b.styleClasses&&(b.styleClasses=null);d===a.doc.highlightFrontier&&(a.doc.modeFrontier=Math.max(a.doc.modeFrontier,++a.doc.highlightFrontier))}return b.styles}function Mb(a,b,d){var c=a.doc,e=a.display;if(!c.mode.startState)return new Da(c,!0,b);var f=Dg(a,b,d),g=f>c.first&&w(c,f-1).stateAfter,h=g?Da.fromSaved(c,g,f):new Da(c,ve(c.mode),f);c.iter(f,b,(function(k){sd(a,k.text,h);var l=h.line;k.stateAfter=l==b-1||0==l%5||l>=e.viewFrom&&le;e++){c&&(c[0]=nd(a,d).mode);var f=a.token(b,d);if(b.pos>b.start)return f}throw Error("Mode "+a.name+" failed to advance stream.")}function Be(a,b,d,c){var e=a.doc,f=e.mode;b=C(e,b);var g=w(e,b.line);d=Mb(a,b.line,d);a=new X(g.text,a.options.tabSize,d);var h;for(c&&(h=[]);(c||a.posa.options.maxHighlightLength){h=!1;g&&sd(a,b,c,m.pos);m.pos=b.length;var p=null}else p=De(td(d,m,c.state,n),f);if(n){var q=n[0].name;q&&(p="m-"+(p?q+" "+p:q))}if(!h||l!=p){for(;kg;--b){if(b<=f.first)return f.first;var h=w(f,b-1),k=h.stateAfter;if(k&&(!d||b+(k instanceof Ac?k.lookAhead:0)<=f.modeFrontier))return b;h=va(h.text,null,a.options.tabSize);if(null==e||c>h)e=b-1,c=h}return e}function Eg(a,b){a.modeFrontier=Math.min(a.modeFrontier,b);if(!(a.highlightFrontierd;c--){var e=w(a,c).stateAfter;if(e&&(!(e instanceof Ac)||c+e.lookAhead=a:k.to>a);(g||(g=[])).push(new Bc(l,k.from,m?null:k.to))}}d=g;var n;if(c)for(g=0;g=e:h.to>e)||h.from==e&&"bookmark"==k.type&&(!f||h.marker.insertLeft))l=null==h.from||(k.inclusiveLeft?h.from<=e:h.fromB(g.to,e.from)||0k||!d.inclusiveLeft&&!k)&&h.push({from:g.from,to:e.from});(0vd(e,d.marker)))var e=d.marker;return e}function He(a,b,d,c,e){a=w(a,b);if(a=Ja&&a.markedSpans)for(b=0;b=k||0>=h&&0<=k)&&(0>=h&&(f.marker.inclusiveRight&&e.inclusiveLeft?0<=B(g.to,d):0=B(g.from,c):0>B(g.from,c))))return!0}}}function Ea(a){for(var b;b=qb(a,!0);)a=b.find(-1,!0).line;return a}function wd(a,b){a=w(a,b);var d=Ea(a);return a==d?b:N(d)}function Ie(a,b){if(b>a.lastLine())return b;var d=w(a,b);if(!Oa(a,d))return b;for(;a=qb(d,!1);)d=a.find(1,!0).line;return N(d)+1}function Oa(a,b){var d=Ja&&b.markedSpans;if(d)for(var c,e=0;eb.maxLineLength&&(b.maxLineLength=c,b.maxLine=d)}))}function Je(a,b){if(!a||/^\s*$/.test(a))return null;b=b.addModeClass?Gg:Hg;return b[a]||(b[a]=a.replace(/\S+/g,"cm-$&"))}function Ke(a,b){var d=M("span",null,null,fa?"padding-right: .1px":null);d={pre:M("pre",[d],"CodeMirror-line"),content:d,col:0,pos:0,cm:a,trailingSpace:!1,splitSpaces:a.getOption("lineWrapping")};b.measure={};for(var c=0;c<=(b.rest?b.rest.length:0);c++){var e=c?b.rest[c-1]:b.line,f=void 0;d.pos=0;d.addToken=Ig;var g=a.display.measure;if(null!=zd)g=zd;else{var h=D(g,document.createTextNode("AخA")),k=Ob(h,0,1).getBoundingClientRect();h=Ob(h,1,2).getBoundingClientRect();E(g);g=k&&k.left!=k.right?zd=3>h.right-k.right:!1}g&&(f=Ia(e,a.doc.direction))&&(d.addToken=Jg(d.addToken,f));d.map=[];var l=b!=a.display.externalMeasured&&N(e);a:{var m=h=k=g=void 0,n=void 0,p=void 0,q=void 0;f=d;l=ze(a,e,l);var r=e.markedSpans,u=e.text,A=0;if(r)for(var Y=u.length,x=0,P=1,K="",Q=0;;){if(Q==x){n=m=h=p="";k=g=null;Q=Infinity;for(var S=[],F=void 0,R=0;Rx||L.collapsed&&H.to==x&&H.from==x)){null!=H.to&&H.to!=x&&Q>H.to&&(Q=H.to,m="");L.className&&(n+=" "+L.className);L.css&&(p=(p?p+";":"")+L.css);L.startStyle&&H.from==x&&(h+=" "+L.startStyle);L.endStyle&&H.to==Q&&(F||(F=[])).push(L.endStyle,H.to);L.title&&((g||(g={})).title=L.title);if(L.attributes)for(var ha in L.attributes)(g||(g={}))[ha]=L.attributes[ha];L.collapsed&&(!k||0>vd(k.marker,L))&&(k=H)}else H.from>x&&Q>H.from&&(Q=H.from)}if(F)for(R=0;R=Y)break;for(S=Math.min(Y,Q);;){if(K){F=x+K.length;k||(R=F>S?K.slice(0,S-x):K,f.addToken(f,R,q?q+n:n,h,x+R.length==Q?m:"",p,g));if(F>=S){K=K.slice(S-x);x=S;break}x=F;h=""}K=u.slice(A,A=l[P++]);q=Je(l[P++],f.cm.options)}}else for(g=1;g=m.offsetWidth&&2T))),h=Ad?v("span","​"):v("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px"),h.setAttribute("cm-text",""),f.call(e,0,0,k.call(g,h)));0==c?(b.measure.map=d.map,b.measure.cache={}):((b.measure.maps||(b.measure.maps=[])).push(d.map),(b.measure.caches||(b.measure.caches=[])).push({}))}fa&&(ha=d.content.lastChild,/\bcm-tab\b/.test(ha.className)||ha.querySelector&&ha.querySelector(".cm-tab"))&&(d.content.className="cm-tab-wrap-hack");W(a,"renderLine",a,b.line,d.pre);d.pre.className&&(d.textClass=ed(d.pre.className,d.textClass||""));return d}function Kg(a){var b=v("span","•","cm-invalidchar");b.title="\\u"+a.charCodeAt(0).toString(16);b.setAttribute("aria-label",b.title);return b}function Ig(a,b,d,c,e,f,g){if(b){if(a.splitSpaces){var h=a.trailingSpace;if(1T?h.appendChild(v("span",[r])):h.appendChild(r);a.map.push(a.pos,a.pos+q,r);a.col+=q;a.pos+=q}if(!p)break;n+=q+1;"\t"==p[0]?(p=a.cm.options.tabSize,p-=a.col%p,q=h.appendChild(v("span",hd(p),"cm-tab")),q.setAttribute("role","presentation"),q.setAttribute("cm-text","\t"),a.col+=p):("\r"==p[0]||"\n"==p[0]?(q=h.appendChild(v("span","\r"==p[0]?"␍":"␤","cm-invalidchar")),q.setAttribute("cm-text",p[0])):(q=a.cm.options.specialCharPlaceholder(p[0]),q.setAttribute("cm-text",p[0]),G&&9>T?h.appendChild(v("span",[q])):h.appendChild(q)),a.col+=1);a.map.push(a.pos,a.pos+1,q);a.pos++}}else a.col+=b.length,h=document.createTextNode(k),a.map.push(a.pos,a.pos+b.length,h),G&&9>T&&(m=!0),a.pos+=b.length;a.trailingSpace=32==k.charCodeAt(b.length-1);if(d||c||e||m||f||g){b=d||"";c&&(b+=c);e&&(b+=e);c=v("span",[h],b,f);if(g)for(var u in g)g.hasOwnProperty(u)&&"style"!=u&&"class"!=u&&c.setAttribute(u,g[u]);return a.content.appendChild(c)}a.content.appendChild(h)}}function Jg(a,b){return function(d,c,e,f,g,h,k){e=e?e+" cm-force-border":"cm-force-border";for(var l=d.pos,m=l+c.length;;){for(var n=void 0,p=0;pl&&n.from<=l);p++);if(n.to>=m)return a(d,c,e,f,g,h,k);a(d,c.slice(0,n.to-l),e,f,null,h,k);f=null;c=c.slice(n.to-l);l=n.to}}}function Le(a,b,d,c){var e=!c&&d.widgetNode;e&&a.map.push(a.pos,a.pos+b,e);!c&&a.cm.display.input.needsContentAttribute&&(e||(e=a.content.appendChild(document.createElement("span"))),e.setAttribute("cm-marker",d.id));e&&(a.cm.display.input.setUneditable(e),a.content.appendChild(e));a.pos+=b;a.trailingSpace=!1}function Me(a,b,d){for(var c=this.line=b,e;c=qb(c,!1);)c=c.find(1,!0).line,(e||(e=[])).push(c);this.size=(this.rest=e)?N(J(this.rest))-d+1:1;this.node=this.text=null;this.hidden=Oa(a,b)}function Dc(a,b,d){var c=[],e;for(e=b;eT&&(a.node.style.zIndex=2));return a.node}function Oe(a,b){var d=a.display.externalMeasured;return d&&d.line==b.line?(a.display.externalMeasured=null,b.measure=d.measure,d.built):Ke(a,b)}function Bd(a,b){var d=b.bgClass?b.bgClass+" "+(b.line.bgClass||""):b.line.bgClass;d&&(d+=" CodeMirror-linebackground");if(b.background)d?b.background.className=d:(b.background.parentNode.removeChild(b.background),b.background=null);else if(d){var c=Qb(b);b.background=c.insertBefore(v("div",null,d),c.firstChild);a.display.input.setUneditable(b.background)}b.line.wrapClass?Qb(b).className=b.line.wrapClass:b.node!=b.text&&(b.node.className="");b.text.className=(b.textClass?b.textClass+" "+(b.line.textClass||""):b.line.textClass)||""}function Pe(a,b,d,c){b.gutter&&(b.node.removeChild(b.gutter),b.gutter=null);b.gutterBackground&&(b.node.removeChild(b.gutterBackground),b.gutterBackground=null);if(b.line.gutterClass){var e=Qb(b);b.gutterBackground=v("div",null,"CodeMirror-gutter-background "+b.line.gutterClass,"left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px; width: "+c.gutterTotalWidth+"px");a.display.input.setUneditable(b.gutterBackground);e.insertBefore(b.gutterBackground,b.text)}e=b.line.gutterMarkers;if(a.options.lineNumbers||e){var f=Qb(b),g=b.gutter=v("div",null,"CodeMirror-gutter-wrapper","left: "+(a.options.fixedGutter?c.fixedPos:-c.gutterTotalWidth)+"px");g.setAttribute("aria-hidden","true");a.display.input.setUneditable(g);f.insertBefore(g,b.text);b.line.gutterClass&&(g.className+=" "+b.line.gutterClass);!a.options.lineNumbers||e&&e["CodeMirror-linenumbers"]||(b.lineNumber=g.appendChild(v("div",pd(a.options,d),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+c.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+a.display.lineNumInnerWidth+"px")));if(e)for(b=0;bd)return{map:a.measure.maps[b],cache:a.measure.caches[b],before:!0}}}function Ed(a,b){if(b>=a.display.viewFrom&&b=a.lineN&&bp;p++){for(;h&&jd(b.line.text.charAt(g.coverStart+h));)--h;for(;g.coverStart+kT&&0==h&&k==g.coverEnd-g.coverStart)var q=c.parentNode.getBoundingClientRect();else{q=Ob(c,h,k).getClientRects();k=Ve;if("left"==m)for(l=0;lT&&((p=!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI)||(null!=Gd?p=Gd:(m=D(a.display.measure,v("span","x")),p=m.getBoundingClientRect(),m=Ob(m,0,1).getBoundingClientRect(),p=Gd=1T)||h||q&&(q.left||q.right)||(q=(q=c.parentNode.getClientRects()[0])?{left:q.left,right:q.left+sb(a.display),top:q.top,bottom:q.bottom}:Ve);c=q.top-b.rect.top;h=q.bottom-b.rect.top;p=(c+h)/2;m=b.view.measure.heights;for(g=0;gb)f=k-h,e=f-1,b>=k&&(g="right");if(null!=e){c=a[l+2];h==k&&d==(c.insertLeft?"left":"right")&&(g=d);if("left"==d&&0==e)for(;l&&a[l-2]==a[l-3]&&a[l-1].insertLeft;)c=a[(l-=3)+2],g="left";if("right"==d&&e==k-h)for(;l=c.text.length?(l=c.text.length,b="before"):0>=l&&(l=0,b="after");if(!k)return g("before"==b?l-1:l,"before"==b);var m=Ib(k,l,b),n=Jb;m=h(l,m,"before"==b);null!=n&&(m.other=h(l,n,"before"!=b));return m}function af(a,b){var d=0;b=C(a.doc,b);a.options.lineWrapping||(d=sb(a.display)*b.ch);b=w(a.doc,b.line);a=Fa(b)+a.display.lineSpace.offsetTop;return{left:d,right:d,top:a,bottom:a+b.height}}function Id(a,b,d,c,e){a=t(a,b,d);a.xRel=e;c&&(a.outside=c);return a}function Jd(a,b,d){var c=a.doc;d+=a.display.viewOffset;if(0>d)return Id(c.first,0,null,-1,-1);var e=$a(c,d),f=c.first+c.size-1;if(e>f)return Id(c.first+c.size-1,w(c,f).text.length,null,1,1);0>b&&(b=0);for(var g=w(c,e);;){f=Og(a,g,e,b,d);var h=void 0;var k=f.ch+(0k)&&(!h||0>vd(h,m.marker))&&(h=m.marker)}if(!h)return f;f=h.find(1);if(f.line==e)return f;g=w(c,e=f.line)}}function bf(a,b,d,c){c-=Hd(b);b=b.text.length;var e=Hb((function(f){return ya(a,d,f-1).bottom<=c}),b,0);b=Hb((function(f){return ya(a,d,f).top>c}),e,b);return{begin:e,end:b}}function cf(a,b,d,c){d||(d=cb(a,b));c=Gc(a,b,ya(a,d,c),"line").top;return bf(a,b,d,c)}function Kd(a,b,d,c){return a.bottom<=d?!1:a.top>d?!0:(c?a.left:a.right)>b}function Og(a,b,d,c,e){e-=Fa(b);var f=cb(a,b),g=Hd(b),h=0,k=b.text.length,l=!0,m=Ia(b,a.doc.direction);m&&(m=(a.options.lineWrapping?Pg:Qg)(a,b,d,f,m,c,e),h=(l=1!=m.level)?m.from:m.to-1,k=l?m.to:m.from-1);var n=null,p=null;m=Hb((function(r){var u=ya(a,f,r);u.top+=g;u.bottom+=g;if(!Kd(u,c,e,!1))return!1;u.top<=e&&u.left<=c&&(n=r,p=u);return!0}),h,k);var q=!1;p?(h=c-p.left=q.bottom?1:0);m=re(b.text,m,1);return Id(d,m,l,q,c-h)}function Qg(a,b,d,c,e,f,g){var h=Hb((function(m){m=e[m];var n=1!=m.level;return Kd(za(a,t(d,n?m.to:m.from,n?"before":"after"),"line",b,c),f,g,!0)}),0,e.length-1),k=e[h];if(0g&&(k=e[h-1])}return k}function Pg(a,b,d,c,e,f,g){g=bf(a,b,c,g);d=g.begin;g=g.end;/\s/.test(b.text.charAt(g-1))&&g--;for(var h=b=null,k=0;k=g||l.to<=d)){var m=ya(a,c,1!=l.level?Math.min(g,l.to)-1:Math.max(d,l.from)).right;m=mm)b=l,h=m}}b||(b=e[e.length-1]);b.fromg&&(b={from:b.from,to:g,level:b.level});return b}function tb(a){if(null!=a.cachedTextHeight)return a.cachedTextHeight;if(null==db){db=v("pre",null,"CodeMirror-line-like");for(var b=0;49>b;++b)db.appendChild(document.createTextNode("x")),db.appendChild(v("br"));db.appendChild(document.createTextNode("x"))}D(a.measure,db);b=db.offsetHeight/50;3=a.display.viewTo)return null;b-=a.display.viewFrom;if(0>b)return null;a=a.display.view;for(var d=0;db)return d}function ma(a,b,d,c){null==b&&(b=a.doc.first);null==d&&(d=a.doc.first+a.doc.size);c||(c=0);var e=a.display;c&&db)&&(e.updateLineNumbers=b);a.curOp.viewChanged=!0;if(b>=e.viewTo)Ja&&wd(a.doc,b)e.viewFrom?Pa(a):(e.viewFrom+=c,e.viewTo+=c);else if(b<=e.viewFrom&&d>=e.viewTo)Pa(a);else if(b<=e.viewFrom){var f=Ic(a,d,d+c,1);f?(e.view=e.view.slice(f.index),e.viewFrom=f.lineN,e.viewTo+=c):Pa(a)}else if(d>=e.viewTo)(f=Ic(a,b,b,-1))?(e.view=e.view.slice(0,f.index),e.viewTo=f.lineN):Pa(a);else{f=Ic(a,b,b,-1);var g=Ic(a,d,d+c,1);f&&g?(e.view=e.view.slice(0,f.index).concat(Dc(a,f.lineN,g.lineN)).concat(e.view.slice(g.index)),e.viewTo+=c):Pa(a)}if(a=e.externalMeasured)d=e.lineN&&b=c.viewTo||(a=c.view[bb(a,b)],null!=a.node&&(a=a.changes||(a.changes=[]),-1==ea(a,d)&&a.push(d)))}function Pa(a){a.display.viewFrom=a.display.viewTo=a.doc.first;a.display.view=[];a.display.viewOffset=0}function Ic(a,b,d,c){var e=bb(a,b),f=a.display.view;if(!Ja||d==a.doc.first+a.doc.size)return{index:e,lineN:d};for(var g=a.display.viewFrom,h=0;hc?0:f.length-1))return null;d+=c*f[e-(0>c?1:0)].size;e+=c}return{index:e,lineN:d}}function ef(a){a=a.display.view;for(var b=0,d=0;d=a.display.viewTo||k.to().liner&&(r=0);r=Math.round(r);A=Math.round(A);h.appendChild(v("div",null,"CodeMirror-selected","position: absolute; left: "+q+"px;\n top: "+r+"px; width: "+(null==u?m-q:u)+"px;\n height: "+(A-r)+"px"))}function e(q,r,u){function A(F,R){return Hc(a,t(q,F),"div",x,R)}function Y(F,R,H){F=cf(a,x,null,F);R="ltr"==R==("after"==H)?"left":"right";H="after"==H?F.begin:F.end-(/\s/.test(x.text.charAt(F.end-1))?2:1);return A(H,R)[R]}var x=w(g,q),P=x.text.length,K,Q,S=Ia(x,g.direction);zg(S,r||0,null==u?P:u,(function(F,R,H,L){var ha="ltr"==H,na=A(F,ha?"left":"right"),ta=A(R-1,ha?"right":"left"),fb=null==r&&0==F,gb=null==u&&R==P,Od=0==L;L=!S||L==S.length-1;3>=ta.top-na.top?(R=(n?fb:gb)&&Od?l:(ha?na:ta).left,c(R,na.top,((n?gb:fb)&&L?m:(ha?ta:na).right)-R,na.bottom)):(ha?(ha=n&&fb&&Od?l:na.left,fb=n?m:Y(F,H,"before"),F=n?l:Y(R,H,"after"),gb=n&&gb&&L?m:ta.right):(ha=n?Y(F,H,"before"):l,fb=!n&&fb&&Od?m:na.right,F=!n&&gb&&L?l:ta.left,gb=n?Y(R,H,"after"):m),c(ha,na.top,fb-ha,na.bottom),na.bottomJc(na,K))K=na;0>Jc(ta,K)&&(K=ta);if(!Q||0>Jc(na,Q))Q=na;0>Jc(ta,Q)&&(Q=ta)}));return{start:K,end:Q}}var f=a.display,g=a.doc,h=document.createDocumentFragment(),k=Se(a.display),l=k.left,m=Math.max(f.sizerWidth,ab(a)-f.sizer.offsetLeft)-k.right,n="ltr"==g.direction;f=b.from();b=b.to();if(f.line==b.line)e(f.line,f.ch,b.ch);else{var p=w(g,f.line);k=w(g,b.line);k=Ea(p)==Ea(k);f=e(f.line,f.ch,k?p.text.length+1:null).end;b=e(b.line,k?0:null,b.ch).start;k&&(f.topa.options.cursorBlinkRate&&(b.cursorDiv.style.visibility="hidden")}}function gf(a){a.hasFocus()||(a.display.input.focus(),a.state.focused||Qd(a))}function Rd(a){a.state.delayingBlurEvent=!0;setTimeout((function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,a.state.focused&&ub(a))}),100)}function Qd(a,b){a.state.delayingBlurEvent&&!a.state.draggingText&&(a.state.delayingBlurEvent=!1);"nocursor"!=a.options.readOnly&&(a.state.focused||(W(a,"focus",a,b),a.state.focused=!0,Wa(a.display.wrapper,"CodeMirror-focused"),a.curOp||a.display.selForContextMenu==a.doc.sel||(a.display.input.reset(),fa&&setTimeout((function(){return a.display.input.reset(!0)}),20)),a.display.input.receivedFocus()),Pd(a))}function ub(a,b){a.state.delayingBlurEvent||(a.state.focused&&(W(a,"blur",a,b),a.state.focused=!1,hb(a.display.wrapper,"CodeMirror-focused")),clearInterval(a.display.blinker),setTimeout((function(){a.state.focused||(a.display.shift=!1)}),150))}function Kc(a){for(var b=a.display,d=b.lineDiv.offsetTop,c=Math.max(0,b.scroller.getBoundingClientRect().top),e=b.lineDiv.getBoundingClientRect().top,f=0,g=0;gT){k=h.node.offsetTop+h.node.offsetHeight;var m=k-d;d=k}else{var n=h.node.getBoundingClientRect();m=n.bottom-n.top;!k&&h.text.firstChild&&(l=h.text.firstChild.getBoundingClientRect().right-n.left-1)}k=h.line.height-m;if(.005k)if(ea.display.sizerWidth&&(l=Math.ceil(l/sb(a.display)),l>a.display.maxLineLength&&(a.display.maxLineLength=l,a.display.maxLine=h.line,a.display.maxLineChanged=!0))}}2=e&&(c=$a(b,Fa(w(b,d))-a.wrapper.clientHeight),e=d)}return{from:c,to:Math.max(e,c+1)}}function Sd(a,b){var d=a.display,c=tb(a.display);0>b.top&&(b.top=0);var e=a.curOp&&null!=a.curOp.scrollTop?a.curOp.scrollTop:d.scroller.scrollTop,f=Dd(a),g={};b.bottom-b.top>f&&(b.bottom=b.top+f);var h=a.doc.height+Cd(d),k=b.toph-c;b.tope+f&&(f=Math.min(b.top,(c?h:b.bottom)-f),f!=e&&(g.scrollTop=f));e=a.options.fixedGutter?0:d.gutters.offsetWidth;f=a.curOp&&null!=a.curOp.scrollLeft?a.curOp.scrollLeft:d.scroller.scrollLeft-e;a=ab(a)-d.gutters.offsetWidth;if(d=b.right-b.left>a)b.right=b.left+a;10>b.left?g.scrollLeft=0:b.lefta+f-3&&(g.scrollLeft=b.right+(d?0:10)-a);return g}function Mc(a,b){null!=b&&(Nc(a),a.curOp.scrollTop=(null==a.curOp.scrollTop?a.doc.scrollTop:a.curOp.scrollTop)+b)}function vb(a){Nc(a);var b=a.getCursor();a.curOp.scrollToPos={from:b,to:b,margin:a.options.cursorScrollMargin}}function Ub(a,b,d){null==b&&null==d||Nc(a);null!=b&&(a.curOp.scrollLeft=b);null!=d&&(a.curOp.scrollTop=d)}function Nc(a){var b=a.curOp.scrollToPos;if(b){a.curOp.scrollToPos=null;var d=af(a,b.from),c=af(a,b.to);jf(a,d,c,b.margin)}}function jf(a,b,d,c){b=Sd(a,{left:Math.min(b.left,d.left),top:Math.min(b.top,d.top)-c,right:Math.max(b.right,d.right),bottom:Math.max(b.bottom,d.bottom)+c});Ub(a,b.scrollLeft,b.scrollTop)}function Vb(a,b){2>Math.abs(a.doc.scrollTop-b)||(La||Td(a,{top:b}),kf(a,b,!0),La&&Td(a),Wb(a,100))}function kf(a,b,d){b=Math.max(0,Math.min(a.display.scroller.scrollHeight-a.display.scroller.clientHeight,b));if(a.display.scroller.scrollTop!=b||d)a.doc.scrollTop=b,a.display.scrollbars.setScrollTop(b),a.display.scroller.scrollTop!=b&&(a.display.scroller.scrollTop=b)}function ib(a,b,d,c){b=Math.max(0,Math.min(b,a.display.scroller.scrollWidth-a.display.scroller.clientWidth));(d?b==a.doc.scrollLeft:2>Math.abs(a.doc.scrollLeft-b))&&!c||(a.doc.scrollLeft=b,lf(a),a.display.scroller.scrollLeft!=b&&(a.display.scroller.scrollLeft=b),a.display.scrollbars.setScrollLeft(b))}function Xb(a){var b=a.display,d=b.gutters.offsetWidth,c=Math.round(a.doc.height+Cd(a.display));return{clientHeight:b.scroller.clientHeight,viewHeight:b.wrapper.clientHeight,scrollWidth:b.scroller.scrollWidth,clientWidth:b.scroller.clientWidth,viewWidth:b.wrapper.clientWidth,barLeft:a.options.fixedGutter?d:0,docHeight:c,scrollHeight:c+Ga(a)+b.barHeight,nativeBarWidth:b.nativeBarWidth,gutterWidth:d}}function wb(a,b){b||(b=Xb(a));var d=a.display.barWidth,c=a.display.barHeight;mf(a,b);for(b=0;4>b&&d!=a.display.barWidth||c!=a.display.barHeight;b++)d!=a.display.barWidth&&a.options.lineWrapping&&Kc(a),mf(a,Xb(a)),d=a.display.barWidth,c=a.display.barHeight}function mf(a,b){var d=a.display,c=d.scrollbars.update(b);d.sizer.style.paddingRight=(d.barWidth=c.right)+"px";d.sizer.style.paddingBottom=(d.barHeight=c.bottom)+"px";d.heightForcer.style.borderBottom=c.bottom+"px solid transparent";c.right&&c.bottom?(d.scrollbarFiller.style.display="block",d.scrollbarFiller.style.height=c.bottom+"px",d.scrollbarFiller.style.width=c.right+"px"):d.scrollbarFiller.style.display="";c.bottom&&a.options.coverGutterNextToScrollbar&&a.options.fixedGutter?(d.gutterFiller.style.display="block",d.gutterFiller.style.height=c.bottom+"px",d.gutterFiller.style.width=b.gutterWidth+"px"):d.gutterFiller.style.display=""}function nf(a){a.display.scrollbars&&(a.display.scrollbars.clear(),a.display.scrollbars.addClass&&hb(a.display.wrapper,a.display.scrollbars.addClass));a.display.scrollbars=new of[a.options.scrollbarStyle]((function(b){a.display.wrapper.insertBefore(b,a.display.scrollbarFiller);z(b,"mousedown",(function(){a.state.focused&&setTimeout((function(){return a.display.input.focus()}),0)}));b.setAttribute("cm-not-content","true")}),(function(b,d){"horizontal"==d?ib(a,b):Vb(a,b)}),a);a.display.scrollbars.addClass&&Wa(a.display.wrapper,a.display.scrollbars.addClass)}function jb(a){a.curOp={cm:a,viewChanged:!1,startHeight:a.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Sg,markArrays:null};a=a.curOp;rb?rb.ops.push(a):a.ownsGroup=rb={ops:[a],delayedCallbacks:[]}}function kb(a){(a=a.curOp)&&Lg(a,(function(b){for(var d=0;d=f.viewTo)||f.maxLineChanged&&e.options.lineWrapping;c.update=c.mustUpdate&&new Oc(e,c.mustUpdate&&{top:c.scrollTop,ensure:c.scrollToPos},c.forceUpdate)}for(d=0;dn;n++){var p=!1;h=za(e,k);var q=l&&l!=k?za(e,l):h;h={left:Math.min(h.left,q.left),top:Math.min(h.top,q.top)-m,right:Math.max(h.left,q.left),bottom:Math.max(h.bottom,q.bottom)+m};q=Sd(e,h);var r=e.doc.scrollTop,u=e.doc.scrollLeft;null!=q.scrollTop&&(Vb(e,q.scrollTop),1l.top+n.top?k=!0:l.bottom+n.top>(window.innerHeight||document.documentElement.clientHeight)&&(k=!1),null==k||Tg||(l=v("div","​",null,"position: absolute;\n top: "+(l.top-m.viewOffset-e.display.lineSpace.offsetTop)+"px;\n height: "+(l.bottom-l.top+Ga(e)+m.barHeight)+"px;\n left: "+l.left+"px; width: "+Math.max(2,l.right-l.left)+"px;"),e.display.lineSpace.appendChild(l),l.scrollIntoView(k),e.display.lineSpace.removeChild(l)))}l=c.maybeHiddenMarkers;k=c.maybeUnhiddenMarkers;if(l)for(m=0;m=a.display.viewTo)){var d=+new Date+a.options.workTime,c=Mb(a,b.highlightFrontier),e=[];b.iter(c.line,Math.min(b.first+b.size,a.display.viewTo+500),(function(f){if(c.line>=a.display.viewFrom){var g=f.styles,h=f.text.length>a.options.maxHighlightLength?Ya(b.mode,c.state):null,k=xe(a,f,c,!0);h&&(c.state=h);f.styles=k.styles;h=f.styleClasses;(k=k.classes)?f.styleClasses=k:h&&(f.styleClasses=null);k=!g||g.length!=f.styles.length||h!=k&&(!h||!k||h.bgClass!=k.bgClass||h.textClass!=k.textClass);for(h=0;!k&&hd)return Wb(a,a.options.workDelay),!0}));b.highlightFrontier=c.line;b.modeFrontier=Math.max(b.modeFrontier,c.line);e.length&&qa(a,(function(){for(var f=0;f=d.viewFrom&&b.visible.to<=d.viewTo&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo)&&d.renderedView==d.view&&0==ef(a))return!1;qf(a)&&(Pa(a),b.dims=Fd(a));var e=c.first+c.size,f=Math.max(b.visible.from-a.options.viewportMargin,c.first),g=Math.min(e,b.visible.to+a.options.viewportMargin);d.viewFromf-d.viewFrom&&(f=Math.max(c.first,d.viewFrom));d.viewTo>g&&20>d.viewTo-g&&(g=Math.min(e,d.viewTo));Ja&&(f=wd(a.doc,f),g=Ie(a.doc,g));c=f!=d.viewFrom||g!=d.viewTo||d.lastWrapHeight!=b.wrapperHeight||d.lastWrapWidth!=b.wrapperWidth;e=a.display;0==e.view.length||f>=e.viewTo||g<=e.viewFrom?(e.view=Dc(a,f,g),e.viewFrom=f):(e.viewFrom>f?e.view=Dc(a,f,e.viewFrom).concat(e.view):e.viewFromg&&(e.view=e.view.slice(0,bb(a,g))));e.viewTo=g;d.viewOffset=Fa(w(a.doc,d.viewFrom));a.display.mover.style.top=d.viewOffset+"px";g=ef(a);if(!c&&0==g&&!b.force&&d.renderedView==d.view&&(null==d.updateLineNumbers||d.updateLineNumbers>=d.viewTo))return!1;a.hasFocus()?f=null:(f=ka())&&ja(a.display.lineDiv,f)?(f={activeElt:f},window.getSelection&&(e=window.getSelection(),e.anchorNode&&e.extend&&ja(a.display.lineDiv,e.anchorNode)&&(f.anchorNode=e.anchorNode,f.anchorOffset=e.anchorOffset,f.focusNode=e.focusNode,f.focusOffset=e.focusOffset))):f=null;4=a.display.viewFrom&&b.visible.to<=a.display.viewTo)break;if(!Ud(a,b))break;Kc(a);c=Xb(a);Tb(a);wb(a,c);Vd(a,c);b.force=!1}b.signal(a,"update",a);if(a.display.viewFrom!=a.display.reportedViewFrom||a.display.viewTo!=a.display.reportedViewTo)b.signal(a,"viewportChange",a,a.display.viewFrom,a.display.viewTo),a.display.reportedViewFrom=a.display.viewFrom,a.display.reportedViewTo=a.display.viewTo}function Td(a,b){b=new Oc(a,b);if(Ud(a,b)){Kc(a);pf(a,b);var d=Xb(a);Tb(a);wb(a,d);Vd(a,d);b.finish()}}function Vg(a,b,d){function c(p){var q=p.nextSibling;fa&&xa&&a.display.currentWheelTarget==p?p.style.display="none":p.parentNode.removeChild(p);return q}var e=a.display,f=a.options.lineNumbers,g=e.lineDiv,h=g.firstChild,k=e.view;e=e.viewFrom;for(var l=0;lT&&(this.gutters.style.zIndex=-1,this.scroller.style.paddingRight=0);fa||La&&Zb||(this.scroller.draggable=!0);a&&(a.appendChild?a.appendChild(this.wrapper):a(this.wrapper));this.reportedViewFrom=this.reportedViewTo=this.viewFrom=this.viewTo=b.first;this.view=[];this.externalMeasured=this.renderedView=null;this.lastWrapHeight=this.lastWrapWidth=this.viewOffset=0;this.updateLineNumbers=null;this.nativeBarWidth=this.barHeight=this.barWidth=0;this.scrollbarsClipped=!1;this.lineNumWidth=this.lineNumInnerWidth=this.lineNumChars=null;this.alignWidgets=!1;this.maxLine=this.cachedCharWidth=this.cachedTextHeight=this.cachedPaddingH=null;this.maxLineLength=0;this.maxLineChanged=!1;this.wheelDX=this.wheelDY=this.wheelStartX=this.wheelStartY=null;this.shift=!1;this.activeTouch=this.selForContextMenu=null;this.gutterSpecs=Xd(c.gutters,c.lineNumbers);rf(this);d.init(this)}function sf(a){var b=a.wheelDeltaX,d=a.wheelDeltaY;null==b&&a.detail&&a.axis==a.HORIZONTAL_AXIS&&(b=a.detail);null==d&&a.detail&&a.axis==a.VERTICAL_AXIS?d=a.detail:null==d&&(d=a.wheelDelta);return{x:b,y:d}}function Xg(a){a=sf(a);a.x*=Ma;a.y*=Ma;return a}function tf(a,b){var d=sf(b),c=d.x;d=d.y;var e=Ma;0===b.deltaMode&&(c=b.deltaX,d=b.deltaY,e=1);var f=a.display,g=f.scroller,h=g.scrollWidth>g.clientWidth,k=g.scrollHeight>g.clientHeight;if(c&&h||d&&k){if(d&&xa&&fa){h=b.target;var l=f.view;a:for(;h!=g;h=h.parentNode)for(var m=0;me?k=Math.max(0,k+e-50):h=Math.min(a.doc.height,h+e+50),Td(a,{top:k,bottom:h})),20>Pc&&0!==b.deltaMode&&(null==f.wheelStartX?(f.wheelStartX=g.scrollLeft,f.wheelStartY=g.scrollTop,f.wheelDX=c,f.wheelDY=d,setTimeout((function(){if(null!=f.wheelStartX){var n=g.scrollLeft-f.wheelStartX,p=g.scrollTop-f.wheelStartY;n=p&&f.wheelDY&&p/f.wheelDY||n&&f.wheelDX&&n/f.wheelDX;f.wheelStartX=f.wheelStartY=null;n&&(Ma=(Ma*Pc+n)/(Pc+1),++Pc)}}),200)):(f.wheelDX+=c,f.wheelDY+=d))):(d&&k&&Vb(a,Math.max(0,g.scrollTop+d*e)),ib(a,Math.max(0,g.scrollLeft+c*e)),(!d||d&&k)&&la(b),f.wheelStartX=null)}}function Ba(a,b,d){a=a&&a.options.selectionsMayTouch;d=b[d];b.sort((function(k,l){return B(k.from(),l.from())}));d=ea(b,d);for(var c=1;cB(a,b.from))return a;if(0>=B(a,b.to))return Ra(b);var d=a.line+b.text.length-(b.to.line-b.from.line)-1,c=a.ch;a.line==b.to.line&&(c+=Ra(b).ch-b.to.ch);return t(d,c)}function Yd(a,b){for(var d=[],c=0;cf-(a.cm?a.cm.options.historyEventDelay:500)||"*"==b.origin.charAt(0))){if(e.lastOp==c){Af(e.done);var h=J(e.done)}else e.done.length&&!J(e.done).ranges?h=J(e.done):1e.undoDepth;)e.done.shift(),e.done[0].ranges||e.done.shift();e.done.push(d);e.generation=++e.maxGeneration;e.lastModTime=e.lastSelTime=f;e.lastOp=e.lastSelOp=c;e.lastOrigin=e.lastSelOrigin=b.origin;k||W(a,"historyAdded")}function Rc(a,b){var d=J(b);d&&d.ranges&&d.equals(a)||b.push(a)}function zf(a,b,d,c){var e=b["spans_"+a.id],f=0;a.iter(Math.max(a.first,d),Math.min(a.first+a.size,c),(function(g){g.markedSpans&&((e||(e=b["spans_"+a.id]={}))[f]=g.markedSpans);++f}))}function Cf(a,b){var d;if(d=b["spans_"+a.id]){for(var c=[],e=0;eB(b,a),c!=0>B(d,a)?(a=b,b=d):c!=0>B(b,d)&&(b=d)),new I(a,b)):new I(d||b,b)}function Sc(a,b,d,c,e){null==e&&(e=a.cm&&(a.cm.display.shift||a.extend));da(a,new ua([be(a.sel.primary(),b,d,e)],0),c)}function Df(a,b,d){for(var c=[],e=a.cm&&(a.cm.display.shift||a.extend),f=0;fB(b.primary().head,a.sel.primary().head)?-1:1);Ff(a,Gf(a,b,c,!0));d&&!1===d.scroll||!a.cm||"nocursor"==a.cm.getOption("readOnly")||vb(a.cm)}function Ff(a,b){b.equals(a.sel)||(a.sel=b,a.cm&&(a.cm.curOp.updateInput=1,a.cm.curOp.selectionChanged=!0,se(a.cm)),aa(a,"cursorActivity",a))}function Hf(a){Ff(a,Gf(a,a.sel,null,!1))}function Gf(a,b,d,c){for(var e,f=0;f=b.ch:h.to>b.ch))){if(e&&(W(k,"beforeCursorEnter"),k.explicitlyCleared))if(f.markedSpans){--g;continue}else break;if(k.atomic){if(d){g=k.find(0>c?1:-1);h=void 0;if(0>c?m:l)g=If(a,g,-c,g&&g.line==b.line?f:null);if(g&&g.line==b.line&&(h=B(g,d))&&(0>c?0>h:0c?-1:1);if(0>c?l:m)d=If(a,d,c,d.line==b.line?f:null);return d?zb(a,d,b,c,e):null}}}return b}function Uc(a,b,d,c,e){c=c||1;b=zb(a,b,d,c,e)||!e&&zb(a,b,d,c,!0)||zb(a,b,d,-c,e)||!e&&zb(a,b,d,-c,!0);return b?b:(a.cantEdit=!0,t(a.first,0))}function If(a,b,d,c){return 0>d&&0==b.ch?b.line>a.first?C(a,t(b.line-1)):null:0a.lastLine())){if(b.from.linee&&(b={from:b.from,to:t(e,w(a,e).text.length),text:[b.text[0]],origin:b.origin});b.removed=Za(a,b.from,b.to);d||(d=Yd(a,b));a.cm?$g(a.cm,b,c):$d(a,b,c);Tc(a,d,Ha);a.cantEdit&&Uc(a,t(a.firstLine(),0))&&(a.cantEdit=!1)}}function $g(a,b,d){var c=a.doc,e=a.display,f=b.from,g=b.to,h=!1,k=f.line;a.options.lineWrapping||(k=N(Ea(w(c,f.line))),c.iter(k,g.line+1,(function(l){if(l==e.maxLine)return h=!0})));-1e.maxLineLength&&(e.maxLine=l,e.maxLineLength=m,e.maxLineChanged=!0,h=!1)})),h&&(a.curOp.updateMaxLine=!0));Eg(c,f.line);Wb(a,400);d=b.text.length-(g.line-f.line)-1;b.full?ma(a):f.line!=g.line||1!=b.text.length||wf(a.doc,b)?ma(a,f.line,g.line+1,d):Qa(a,f.line,"text");d=wa(a,"changes");if((c=wa(a,"change"))||d)b={from:f,to:g,text:b.text,removed:b.removed,origin:b.origin},c&&aa(a,"change",a,b),d&&(a.curOp.changeObjs||(a.curOp.changeObjs=[])).push(b);a.display.selForContextMenu=null}function Bb(a,b,d,c,e){c||(c=d);0>B(c,d)&&(c=[c,d],d=c[0],c=c[1]);"string"==typeof b&&(b=a.splitLines(b));Ab(a,{from:d,to:c,text:b,origin:e})}function Pf(a,b,d,c){d=B(f.from,J(c).to);){var g=c.pop();if(0>B(g.from,f.from)){f.from=g.from;break}}c.push(f)}qa(a,(function(){for(var h=c.length-1;0<=h;h--)Bb(a.doc,"",c[h].from,c[h].to,"+delete");vb(a)}))}function de(a,b,d){b=re(a.text,b+d,d);return 0>b||b>a.text.length?null:b}function ee(a,b,d){a=de(a,b.ch,d);return null==a?null:new t(b.line,a,0>d?"after":"before")}function fe(a,b,d,c,e){if(a&&("rtl"==b.doc.direction&&(e=-e),a=Ia(d,b.doc.direction))){a=0>e?J(a):a[0];var f=0>e==(1==a.level)?"after":"before";if(0e?d.text.length-1:0;var k=ya(b,g,h).top;h=Hb((function(l){return ya(b,g,l).top==k}),0>e==(1==a.level)?a.from:a.to-1,h);"before"==f&&(h=de(d,h,1))}else h=0>e?a.to:a.from;return new t(c,h,f)}return new t(c,0>e?d.text.length:0,0>e?"before":"after")}function ih(a,b,d,c){var e=Ia(b,a.doc.direction);if(!e)return ee(b,d,c);d.ch>=b.text.length?(d.ch=b.text.length,d.sticky="before"):0>=d.ch&&(d.ch=0,d.sticky="after");var f=Ib(e,d.ch,d.sticky),g=e[f];if("ltr"==a.doc.direction&&0==g.level%2&&(0d.ch:g.fromc,p=h(d,n?1:-1);if(null!=p&&(n?p<=g.to&&p<=m.end:p>=g.from&&p>=m.begin))return new t(d.line,p,n?"before":"after")}g=function(q,r,u){for(var A=function(K,Q){return Q?new t(d.line,h(K,1),"before"):new t(d.line,K,"after")};0<=q&&qT&&27==a.keyCode&&(a.returnValue=!1);var b=a.keyCode;this.display.shift=16==b||a.shiftKey;var d=cg(this,a);Aa&&(ge=d?b:null,!d&&88==b&&!lh&&(xa?a.metaKey:a.ctrlKey)&&this.replaceSelection("",null,"cut"));La&&!xa&&!d&&46==b&&a.shiftKey&&!a.ctrlKey&&document.execCommand&&document.execCommand("cut");18!=b||/\bCodeMirror-crosshair\b/.test(this.display.lineDiv.className)||mh(this)}}function mh(a){function b(c){18!=c.keyCode&&c.altKey||(hb(d,"CodeMirror-crosshair"),sa(document,"keyup",b),sa(document,"mouseover",b))}var d=a.display.lineDiv;Wa(d,"CodeMirror-crosshair");z(document,"keyup",b);z(document,"mouseover",b)}function eg(a){16==a.keyCode&&(this.doc.sel.shift=!1);Z(this,a)}function fg(a){if(!(a.target&&a.target!=this.display.input.getField()||Ka(this.display,a)||Z(this,a)||a.ctrlKey&&!a.altKey||xa&&a.metaKey)){var b=a.keyCode,d=a.charCode;if(Aa&&b==ge)ge=null,la(a);else if(!Aa||a.which&&!(10>a.which)||!cg(this,a))if(b=String.fromCharCode(null==d?b:d),"\b"!=b&&!kh(this,a,b))this.display.input.onKeyPress(a)}}function nh(a,b){var d=+new Date;if(jc&&jc.compare(d,a,b))return kc=jc=null,"triple";if(kc&&kc.compare(d,a,b))return jc=new he(d,a,b),kc=null,"double";kc=new he(d,a,b);jc=null;return"single"}function gg(a){var b=this.display;if(!(Z(this,a)||b.activeTouch&&b.input.supportsTouch()))if(b.input.ensurePolled(),b.shift=a.shiftKey,Ka(b,a))fa||(b.scroller.draggable=!1,setTimeout((function(){return b.scroller.draggable=!0}),100));else if(!Zc(this,a,"gutterClick",!0)){var d=eb(this,a),c=ue(a),e=d?nh(d,c):"single";window.focus();1==c&&this.state.selectingText&&this.state.selectingText(a);if(!d||!oh(this,c,d,e,a))if(1==c)d?ph(this,d,e,a):(a.target||a.srcElement)==b.scroller&&la(a);else if(2==c)d&&Sc(this.doc,d),setTimeout((function(){return b.input.focus()}),20);else if(3==c)if(ie)this.display.input.onContextMenu(a);else Rd(this)}}function oh(a,b,d,c,e){var f="Click";"double"==c?f="Double"+f:"triple"==c&&(f="Triple"+f);return ic(a,Xf((1==b?"Left":2==b?"Middle":"Right")+f,e),e,(function(g){"string"==typeof g&&(g=hc[g]);if(!g)return!1;var h=!1;try{a.isReadOnly()&&(a.state.suppressEdits=!0),h=g(a,d)!=Yc}finally{a.state.suppressEdits=!1}return h}))}function ph(a,b,d,c){G?setTimeout(fd(gf,a),0):a.curOp.focus=ka();var e=a.getOption("configureMouse");e=e?e(a,d,c):{};null==e.unit&&(e.unit=(qh?c.shiftKey&&c.metaKey:c.altKey)?"rectangle":"single"==d?"char":"double"==d?"word":"line");if(null==e.extend||a.doc.extend)e.extend=a.doc.extend||c.shiftKey;null==e.addNew&&(e.addNew=xa?c.metaKey:c.ctrlKey);null==e.moveOnDrag&&(e.moveOnDrag=!(xa?c.altKey:c.ctrlKey));var f=a.doc.sel,g;a.options.dragDrop&&rh&&!a.isReadOnly()&&"single"==d&&-1<(g=f.contains(b))&&(0>B((g=f.ranges[g]).from(),b)||0b.xRel)?sh(a,c,b,e):th(a,c,b,e)}function sh(a,b,d,c){var e=a.display,f=!1,g=ba(a,(function(l){fa&&(e.scroller.draggable=!1);a.state.draggingText=!1;a.state.delayingBlurEvent&&(a.hasFocus()?a.state.delayingBlurEvent=!1:Rd(a));sa(e.wrapper.ownerDocument,"mouseup",g);sa(e.wrapper.ownerDocument,"mousemove",h);sa(e.scroller,"dragstart",k);sa(e.scroller,"drop",g);f||(la(l),c.addNew||Sc(a.doc,d,null,null,c.extend),fa&&!$c||G&&9==T?setTimeout((function(){e.wrapper.ownerDocument.body.focus({preventScroll:!0});e.input.focus()}),20):e.input.focus())})),h=function(l){f=f||10<=Math.abs(b.clientX-l.clientX)+Math.abs(b.clientY-l.clientY)},k=function(){return f=!0};fa&&(e.scroller.draggable=!0);a.state.draggingText=g;g.copy=!c.moveOnDrag;z(e.wrapper.ownerDocument,"mouseup",g);z(e.wrapper.ownerDocument,"mousemove",h);z(e.scroller,"dragstart",k);z(e.scroller,"drop",g);a.state.delayingBlurEvent=!0;setTimeout((function(){return e.input.focus()}),20);e.scroller.dragDrop&&e.scroller.dragDrop()}function hg(a,b,d){if("char"==d)return new I(b,b);if("word"==d)return a.findWordAt(b);if("line"==d)return new I(t(b.line,0),C(a.doc,t(b.line+1,0)));a=d(a,b);return new I(a.from,a.to)}function th(a,b,d,c){function e(x){if(0!=B(q,x))if(q=x,"rectangle"==c.unit){var P=[],K=a.options.tabSize,Q=va(w(k,d.line).text,d.ch,K),S=va(w(k,x.line).text,x.ch,K),F=Math.min(Q,S);Q=Math.max(Q,S);S=Math.min(d.line,x.line);for(var R=Math.min(a.lastLine(),Math.max(d.line,x.line));S<=R;S++){var H=w(k,S).text,L=gd(H,F,K);F==Q?P.push(new I(t(S,L),t(S,L))):H.length>L&&P.push(new I(t(S,L),t(S,gd(H,Q,K))))}P.length||P.push(new I(d,d));da(k,Ba(a,l.ranges.slice(0,n).concat(P),n),{origin:"*mouse",scroll:!1});a.scrollIntoView(x)}else P=p,F=hg(a,x,c.unit),x=P.anchor,0=Q.to||K.liner.bottom?20:0;S&&setTimeout(ba(a,(function(){u==P&&(h.scroller.scrollTop+=S,f(x))})),50)}}function g(x){a.state.selectingText=!1;u=Infinity;x&&(la(x),h.input.focus());sa(h.wrapper.ownerDocument,"mousemove",A);sa(h.wrapper.ownerDocument,"mouseup",Y);k.history.lastSelOrigin=null}G&&Rd(a);var h=a.display,k=a.doc;la(b);var l=k.sel,m=l.ranges;if(c.addNew&&!c.extend){var n=k.sel.contains(d);var p=-1f:0=Math.floor(a.display.gutters.getBoundingClientRect().right))return!1;c&&la(b);c=a.display;var g=c.lineDiv.getBoundingClientRect();if(f>g.bottom||!wa(a,d))return kd(b);f-=g.top-c.viewOffset;for(g=0;g=e)return e=$a(a.doc,f),W(a,d,a,e,a.display.gutterSpecs[g].className,b),kd(b)}}function ig(a,b){var d;(d=Ka(a.display,b))||(d=wa(a,"gutterContextMenu")?Zc(a,b,"gutterContextMenu",!1):!1);if(!d&&!Z(a,b,"contextmenu")&&!ie)a.display.input.onContextMenu(b)}function jg(a){a.display.wrapper.className=a.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+a.options.theme.replace(/(^|\s)\s*/g," cm-s-");Sb(a)}function vh(a,b,d){!b!=!(d&&d!=Fb)&&(d=a.display.dragFunctions,b=b?z:sa,b(a.display.scroller,"dragstart",d.start),b(a.display.scroller,"dragenter",d.enter),b(a.display.scroller,"dragover",d.over),b(a.display.scroller,"dragleave",d.leave),b(a.display.scroller,"drop",d.drop))}function wh(a){a.options.lineWrapping?(Wa(a.display.wrapper,"CodeMirror-wrap"),a.display.sizer.style.minWidth="",a.display.sizerWidth=null):(hb(a.display.wrapper,"CodeMirror-wrap"),yd(a));Md(a);ma(a);Sb(a);setTimeout((function(){return wb(a)}),100)}function U(a,b){var d=this;if(!(this instanceof U))return new U(a,b);this.options=b=b?Xa(b):{};Xa(kg,b,!1);var c=b.value;"string"==typeof c?c=new oa(c,b.mode,null,b.lineSeparator,b.direction):b.mode&&(c.modeOption=b.mode);this.doc=c;var e=new U.inputStyles[b.inputStyle](this);a=this.display=new Wg(a,c,e,b);a.wrapper.CodeMirror=this;jg(this);b.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");nf(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new Va,keySeq:null,specialChars:null};b.autofocus&&!Zb&&a.input.focus();G&&11>T&&setTimeout((function(){return d.display.input.reset(!0)}),20);xh(this);lg||(eh(),lg=!0);jb(this);this.curOp.forceUpdate=!0;xf(this,c);b.autofocus&&!Zb||this.hasFocus()?setTimeout((function(){d.hasFocus()&&!d.state.focused&&Qd(d)}),20):ub(this);for(var f in ad)if(ad.hasOwnProperty(f))ad[f](this,b[f],Fb);qf(this);b.finishInit&&b.finishInit(this);for(c=0;cT?z(c.scroller,"dblclick",ba(a,(function(h){if(!Z(a,h)){var k=eb(a,h);!k||Zc(a,h,"gutterClick",!0)||Ka(a.display,h)||(la(h),h=a.findWordAt(k),Sc(a.doc,h.anchor,h.head))}}))):z(c.scroller,"dblclick",(function(h){return Z(a,h)||la(h)}));z(c.scroller,"contextmenu",(function(h){return ig(a,h)}));z(c.input.getField(),"contextmenu",(function(h){c.scroller.contains(h.target)||ig(a,h)}));var e,f={end:0};z(c.scroller,"touchstart",(function(h){var k;if(k=!Z(a,h))1!=h.touches.length?k=!1:(k=h.touches[0],k=1>=k.radiusX&&1>=k.radiusY),k=!k;k&&!Zc(a,h,"gutterClick",!0)&&(c.input.ensurePolled(),clearTimeout(e),k=+new Date,c.activeTouch={start:k,moved:!1,prev:300>=k-f.end?f:null},1==h.touches.length&&(c.activeTouch.left=h.touches[0].pageX,c.activeTouch.top=h.touches[0].pageY))}));z(c.scroller,"touchmove",(function(){c.activeTouch&&(c.activeTouch.moved=!0)}));z(c.scroller,"touchend",(function(h){var k=c.activeTouch;if(k&&!Ka(c,h)&&null!=k.left&&!k.moved&&300>new Date-k.start){var l=a.coordsChar(c.activeTouch,"page");k=!k.prev||d(k,k.prev)?new I(l,l):!k.prev.prev||d(k,k.prev.prev)?a.findWordAt(l):new I(t(l.line,0),C(a.doc,t(l.line+1,0)));a.setSelection(k.anchor,k.head);a.focus();la(h)}b()}));z(c.scroller,"touchcancel",b);z(c.scroller,"scroll",(function(){c.scroller.clientHeight&&(Vb(a,c.scroller.scrollTop),ib(a,c.scroller.scrollLeft,!0),W(a,"scroll",a))}));z(c.scroller,"mousewheel",(function(h){return tf(a,h)}));z(c.scroller,"DOMMouseScroll",(function(h){return tf(a,h)}));z(c.wrapper,"scroll",(function(){return c.wrapper.scrollTop=c.wrapper.scrollLeft=0}));c.dragFunctions={enter:function(h){Z(a,h)||Kb(h)},over:function(h){if(!Z(a,h)){var k=eb(a,h);if(k){var l=document.createDocumentFragment();Nd(a,k,l);a.display.dragCursor||(a.display.dragCursor=v("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),a.display.lineSpace.insertBefore(a.display.dragCursor,a.display.cursorDiv));D(a.display.dragCursor,l)}Kb(h)}},start:function(h){if(G&&(!a.state.draggingText||100>+new Date-Uf))Kb(h);else if(!Z(a,h)&&!Ka(a.display,h)&&(h.dataTransfer.setData("Text",a.getSelection()),h.dataTransfer.effectAllowed="copyMove",h.dataTransfer.setDragImage&&!$c)){var k=v("img",null,null,"position: fixed; left: 0; top: 0;");k.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";Aa&&(k.width=k.height=1,a.display.wrapper.appendChild(k),k._top=k.offsetTop);h.dataTransfer.setDragImage(k,0,0);Aa&&k.parentNode.removeChild(k)}},drop:ba(a,dh),leave:function(h){Z(a,h)||Tf(a)}};var g=c.input.getField();z(g,"keyup",(function(h){return eg.call(a,h)}));z(g,"keydown",ba(a,dg));z(g,"keypress",ba(a,fg));z(g,"focus",(function(h){return Qd(a,h)}));z(g,"blur",(function(h){return ub(a,h)}))}function lc(a,b,d,c){var e=a.doc,f;null==d&&(d="add");"smart"==d&&(e.mode.indent?f=Mb(a,b).state:d="prev");var g=a.options.tabSize,h=w(e,b),k=va(h.text,null,g);h.stateAfter&&(h.stateAfter=null);var l=h.text.match(/^\s*/)[0];if(!c&&!/\S/.test(h.text)){var m=0;d="not"}else if("smart"==d&&(m=e.mode.indent(f,h.text.slice(l.length),h.text),m==Yc||150e.first?va(w(e,b-1).text,null,g):0:"add"==d?m=k+a.options.indentUnit:"subtract"==d?m=k-a.options.indentUnit:"number"==typeof d&&(m=k+d);m=Math.max(0,m);d="";c=0;if(a.options.indentWithTabs)for(a=Math.floor(m/g);a;--a)c+=g,d+="\t";cg,k=me(b),l=null;if(h&&1g?"cut":"+input")};Ab(a.doc,p);aa(a,"inputRead",a,p)}b&&!h&&mg(a,b);vb(a);2>a.curOp.updateInput&&(a.curOp.updateInput=m);a.curOp.typing=!0;a.state.pasteIncoming=a.state.cutIncoming=-1}function ng(a,b){var d=a.clipboardData&&a.clipboardData.getData("Text");if(d)return a.preventDefault(),b.isReadOnly()||b.options.disableInput||qa(b,(function(){return le(b,d,0,null,"paste")})),!0}function mg(a,b){if(a.options.electricChars&&a.options.smartIndent)for(var d=a.doc.sel,c=d.ranges.length-1;0<=c;c--){var e=d.ranges[c];if(!(100A:56320<=A&&57343>A)?2:1))),-d)}else A=e?ih(a.cm,k,b,d):ee(k,b,d);if(null==A){if(u=!u)u=b.line+l,u=a.first+a.size?u=!1:(b=new t(u,b.ch,b.sticky),u=k=w(a,u));if(u)b=fe(e,a.cm,k,b.line,l);else return!1}else b=A;return!0}var g=b,h=d,k=w(a,b.line),l=e&&"rtl"==a.direction?-d:d;if("char"==c||"codepoint"==c)f();else if("column"==c)f(!0);else if("word"==c||"group"==c)for(var m=null,n="group"==c,p=a.cm&&a.cm.getHelper(b,"wordChars"),q=!0;!(0>d)||f(!q);q=!1){var r=k.text.charAt(b.ch)||"\n";r=vc(r,p)?"w":n&&"\n"==r?"n":!n||/\s/.test(r)?null:"p";!n||q||r||(r="s");if(m&&m!=r){0>d&&(d=1,f(),b.sticky="after");break}r&&(m=r);if(0d?0>=g:g>=e.height){b.hitSide=!0;break}g+=5*d}return b}function sg(a,b){var d=Ed(a,b.line);if(!d||d.hidden)return null;var c=w(a.doc,b.line);d=Te(d,c,b.line);a=Ia(c,a.doc.direction);c="left";a&&(c=Ib(a,b.ch)%2?"right":"left");b=Ue(d.map,b.ch,c);b.offset="right"==b.collapse?b.end:b.start;return b}function yh(a){for(;a;a=a.parentNode)if(/CodeMirror-gutter-wrapper/.test(a.className))return!0;return!1}function Gb(a,b){b&&(a.bad=!0);return a}function zh(a,b,d,c,e){function f(q){return function(r){return r.id==q}}function g(){m&&(l+=n,p&&(l+=n),m=p=!1)}function h(q){q&&(g(),l+=q)}function k(q){if(1==q.nodeType){var r=q.getAttribute("cm-text");if(r)h(r);else{r=q.getAttribute("cm-marker");var u;if(r)q=a.findMarks(t(c,0),t(e+1,0),f(+r)),q.length&&(u=q[0].find(0))&&h(Za(a.doc,u.from,u.to).join(n));else if("false"!=q.getAttribute("contenteditable")&&(u=/^(pre|div|p|li|table|br)$/i.test(q.nodeName),/^br$/i.test(q.nodeName)||0!=q.textContent.length)){u&&g();for(r=0;rq?k.map:l[q],u=0;uq?a.line:a.rest[q]);q=r[u]+p;if(0>p||A!=m)q=r[u+(p?1:0)];return t(n,q)}}}var e=a.text.firstChild,f=!1;if(!b||!ja(e,b))return Gb(t(N(a.line),0),!0);if(b==e&&(f=!0,b=e.childNodes[d],d=0,!b))return d=a.rest?J(a.rest):a.line,Gb(t(N(d),d.text.length),f);var g=3==b.nodeType?b:null,h=b;g||1!=b.childNodes.length||3!=b.firstChild.nodeType||(g=b.firstChild,d&&(d=g.nodeValue.length));for(;h.parentNode!=e;)h=h.parentNode;var k=a.measure,l=k.maps;if(b=c(g,h,d))return Gb(b,f);e=h.nextSibling;for(g=g?g.nodeValue.length-d:0;e;e=e.nextSibling){if(b=c(e,e.firstChild,0))return Gb(t(b.line,b.ch-g),f);g+=e.textContent.length}for(h=h.previousSibling;h;h=h.previousSibling){if(b=c(h,h.firstChild,-1))return Gb(t(b.line,b.ch+d),f);d+=h.textContent.length}}var pa=navigator.userAgent,tg=navigator.platform,La=/gecko\/\d/i.test(pa),ug=/MSIE \d/.test(pa),vg=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(pa),cd=/Edge\/(\d+)/.exec(pa),G=ug||vg||cd,T=G&&(ug?document.documentMode||6:+(cd||vg)[1]),fa=!cd&&/WebKit\//.test(pa),Bh=fa&&/Qt\/\d+\.\d+/.test(pa),Ec=!cd&&/Chrome\//.test(pa),Aa=/Opera\//.test(pa),$c=/Apple Computer/.test(navigator.vendor),Ch=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(pa),Tg=/PhantomJS/.test(pa),mc=$c&&(/Mobile\/\w+/.test(pa)||2lb)),ie=La||G&&9<=T,hb=function(a,b){var d=a.className;if(b=y(b).exec(d)){var c=d.slice(b.index+b[0].length);a.className=d.slice(0,b.index)+(c?b[1]+c:"")}};var Ob=document.createRange?function(a,b,d,c){var e=document.createRange();e.setEnd(c||a,d);e.setStart(a,b);return e}:function(a,b,d){var c=document.body.createTextRange();try{c.moveToElementText(a.parentNode)}catch(e){return c}c.collapse(!0);c.moveEnd("character",d);c.moveStart("character",b);return c};var nc=function(a){a.select()};mc?nc=function(a){a.selectionStart=0;a.selectionEnd=a.value.length}:G&&(nc=function(a){try{a.select()}catch(b){}});var Va=function(){this.f=this.id=null;this.time=0;this.handler=fd(this.onTimeout,this)};Va.prototype.onTimeout=function(a){a.id=0;a.time<=+new Date?a.f():setTimeout(a.handler,a.time-+new Date)};Va.prototype.set=function(a,b){this.f=b;b=+new Date+a;if(!this.id||b=r?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(r):1424<=r&&1524>=r?"R":1536<=r&&1785>=r?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(r-1536):1774<=r&&2220>=r?"r":8192<=r&&8203>=r?"w":8204==r?"b":"L";q.call(p,r)}n=0;for(p=k;nT)return!1;var a=v("div");return"draggable"in a||"dragDrop"in a}(),Ad,zd,me=3!="\n\nb".split(/\n/).length?function(a){for(var b=0,d=[],c=a.length;b<=c;){var e=a.indexOf("\n",b);-1==e&&(e=a.length);var f=a.slice(b,"\r"==a.charAt(e-1)?e-1:e),g=f.indexOf("\r");-1!=g?(d.push(f.slice(0,g)),b+=g+1):(d.push(f),b=e+1)}return d}:function(a){return a.split(/\r\n?|\n/)},Eh=window.getSelection?function(a){try{return a.selectionStart!=a.selectionEnd}catch(b){return!1}}:function(a){try{var b=a.ownerDocument.selection.createRange()}catch(d){}return b&&b.parentElement()==a?0!=b.compareEndPoints("StartToEnd",b):!1},lh=function(){var a=v("div");if("oncopy"in a)return!0;a.setAttribute("oncopy","return;");return"function"==typeof a.oncopy}(),Gd=null,ld={},ob={},pb={},X=function(a,b,d){this.pos=this.start=0;this.string=a;this.tabSize=b||8;this.lineStart=this.lastColumnPos=this.lastColumnValue=0;this.lineOracle=d};X.prototype.eol=function(){return this.pos>=this.string.length};X.prototype.sol=function(){return this.pos==this.lineStart};X.prototype.peek=function(){return this.string.charAt(this.pos)||void 0};X.prototype.next=function(){if(this.posb};X.prototype.eatSpace=function(){for(var a=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>a};X.prototype.skipToEnd=function(){this.pos=this.string.length};X.prototype.skipTo=function(a){a=this.string.indexOf(a,this.pos);if(-1this.maxLookAhead&&(this.maxLookAhead=a);return b};Da.prototype.baseToken=function(a){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=a;)this.baseTokenPos+=2;var b=this.baseTokens[this.baseTokenPos+1];return{type:b&&b.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-a}};Da.prototype.nextLine=function(){this.line++;0T&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};mb.prototype.update=function(a){var b=a.scrollWidth>a.clientWidth+1,d=a.scrollHeight>a.clientHeight+1,c=a.nativeBarWidth;d?(this.vert.style.display="block",this.vert.style.bottom=b?c+"px":"0",this.vert.firstChild.style.height=Math.max(0,a.scrollHeight-a.clientHeight+(a.viewHeight-(b?c:0)))+"px"):(this.vert.scrollTop=0,this.vert.style.display="",this.vert.firstChild.style.height="0");b?(this.horiz.style.display="block",this.horiz.style.right=d?c+"px":"0",this.horiz.style.left=a.barLeft+"px",this.horiz.firstChild.style.width=Math.max(0,a.scrollWidth-a.clientWidth+(a.viewWidth-a.barLeft-(d?c:0)))+"px"):(this.horiz.style.display="",this.horiz.firstChild.style.width="0");!this.checkedZeroWidth&&0=B(a,c.to()))return d}return-1};var I=function(a,b){this.anchor=a;this.head=b};I.prototype.from=function(){return zc(this.anchor,this.head)};I.prototype.to=function(){return yc(this.anchor,this.head)};I.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch};cc.prototype={chunkSize:function(){return this.lines.length},removeInner:function(a,b){for(var d=a,c=a+b;dthis.size-b&&(1=this.children.length)){var a=this;do{var b=a.children.splice(a.children.length-5,5);b=new dc(b);if(a.parent){a.size-=b.size;a.height-=b.height;var d=ea(a.parent.children,a);a.parent.children.splice(d+1,0,b)}else d=new dc(a.children),d.parent=a,a.children=[d,b],a=d;b.parent=a.parent}while(10a.display.maxLineLength&&(a.display.maxLine=f,a.display.maxLineLength=g,a.display.maxLineChanged=!0);null!=d&&a&&this.collapsed&&ma(a,d,c+1);this.lines.length=0;this.explicitlyCleared=!0;this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,a&&Hf(a.doc));a&&aa(a,"markerCleared",a,this,d,c);b&&kb(a);this.parent&&this.parent.clear()}};Ta.prototype.find=function(a,b){null==a&&"bookmark"==this.type&&(a=1);for(var d,c,e=0;eB(h.head,h.anchor),a[f]=new I(h?k:g,h?g:k)):a[f]=new I(g,g)}a=new ua(a,this.sel.primIndex)}b=a;for(a=c.length-1;0<=a;a--)Ab(this,c[a]);b?Ef(this,b):this.cm&&vb(this.cm)})),undo:ca((function(){Vc(this,"undo")})),redo:ca((function(){Vc(this,"redo")})),undoSelection:ca((function(){Vc(this,"undo",!0)})),redoSelection:ca((function(){Vc(this,"redo",!0)})),setExtending:function(a){this.extend=a},getExtending:function(){return this.extend},historySize:function(){for(var a=this.history,b=0,d=0,c=0;c=a.ch)&&b.push(e.marker.parent||e.marker)}return b},findMarks:function(a,b,d){a=C(this,a);b=C(this,b);var c=[],e=a.line;this.iter(a.line,b.line+1,(function(f){if(f=f.markedSpans)for(var g=0;g=h.to||null==h.from&&e!=a.line||null!=h.from&&e==b.line&&h.from>=b.ch||d&&!d(h.marker)||c.push(h.marker.parent||h.marker)}++e}));return c},getAllMarks:function(){var a=[];this.iter((function(b){if(b=b.markedSpans)for(var d=0;da)return b=a,!0;a-=e;++d}));return C(this,t(d,b))},indexFromPos:function(a){a=C(this,a);var b=a.ch;if(a.linea.ch)return 0;var d=this.lineSeparator().length;this.iter(this.first,a.line,(function(c){b+=c.text.length+d}));return b},copy:function(a){var b=new oa(od(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);b.scrollTop=this.scrollTop;b.scrollLeft=this.scrollLeft;b.sel=this.sel;b.extend=!1;a&&(b.history.undoDepth=this.history.undoDepth,b.setHistory(this.getHistory()));return b},linkedDoc:function(a){a||(a={});var b=this.first,d=this.first+this.size;null!=a.from&&a.from>b&&(b=a.from);null!=a.to&&a.toqc;qc++)Ua[qc+48]=Ua[qc+96]=String(qc);for(var dd=65;90>=dd;dd++)Ua[dd]=String.fromCharCode(dd);for(var rc=1;12>=rc;rc++)Ua[rc+111]=Ua[rc+63235]="F"+rc;var gc={basic:{Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},pcDefault:{"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},emacsy:{"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},macDefault:{"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]}};gc["default"]=xa?gc.macDefault:gc.pcDefault;var hc={selectAll:Jf,singleSelection:function(a){return a.setSelection(a.getCursor("anchor"),a.getCursor("head"),Ha)},killLine:function(a){return Eb(a,(function(b){if(b.empty()){var d=w(a.doc,b.head.line).text.length;return b.head.ch==d&&b.head.linea.doc.first){var g=w(a.doc,e.line-1).text;g&&(e=new t(e.line,1),a.replaceRange(f.charAt(0)+a.doc.lineSeparator()+g.charAt(g.length-1),t(e.line-1,g.length-1),e,"+transpose"))}d.push(new I(e,e))}a.setSelections(d)}))},newlineAndIndent:function(a){return qa(a,(function(){for(var b=a.listSelections(),d=b.length-1;0<=d;d--)a.replaceRange(a.doc.lineSeparator(),b[d].anchor,b[d].head,"+input");b=a.listSelections();for(d=0;da&&0==B(b,this.pos)&&d==this.button};var kc,jc,Fb={toString:function(){return"CodeMirror.Init"}},kg={},ad={};U.defaults=kg;U.optionHandlers=ad;var ke=[];U.defineInitHook=function(a){return ke.push(a)};var ra=null,O=function(a){this.cm=a;this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null;this.polling=new Va;this.composing=null;this.gracePeriod=!1;this.readDOMTimeout=null};O.prototype.init=function(a){function b(h){for(h=h.target;h;h=h.parentNode){if(h==g)return!0;if(/\bCodeMirror-(?:line)?widget\b/.test(h.className))break}return!1}function d(h){if(b(h)&&!Z(f,h)){if(f.somethingSelected())ra={lineWise:!1,text:f.getSelections()},"cut"==h.type&&f.replaceSelection("",null,"cut");else if(f.options.lineWiseCopyCut){var k=og(f);ra={lineWise:!0,text:k.text};"cut"==h.type&&f.operation((function(){f.setSelections(k.ranges,0,Ha);f.replaceSelection("",null,"cut")}))}else return;if(h.clipboardData){h.clipboardData.clearData();var l=ra.text.join("\n");h.clipboardData.setData("Text",l);if(h.clipboardData.getData("Text")==l){h.preventDefault();return}}var m=qg();h=m.firstChild;f.display.lineSpace.insertBefore(m,f.display.lineSpace.firstChild);h.value=ra.text.join("\n");var n=ka();nc(h);setTimeout((function(){f.display.lineSpace.removeChild(m);n.focus();n==g&&e.showPrimarySelection()}),50)}}var c=this,e=this,f=e.cm,g=e.div=a.lineDiv;g.contentEditable=!0;pg(g,f.options.spellcheck,f.options.autocorrect,f.options.autocapitalize);z(g,"paste",(function(h){!b(h)||Z(f,h)||ng(h,f)||11>=T&&setTimeout(ba(f,(function(){return c.updateFromDOM()})),20)}));z(g,"compositionstart",(function(h){c.composing={data:h.data,done:!1}}));z(g,"compositionupdate",(function(h){c.composing||(c.composing={data:h.data,done:!1})}));z(g,"compositionend",(function(h){c.composing&&(h.data!=c.composing.data&&c.readFromDOMSoon(),c.composing.done=!0)}));z(g,"touchstart",(function(){return e.forceCompositionEnd()}));z(g,"input",(function(){c.composing||c.readFromDOMSoon()}));z(g,"copy",d);z(g,"cut",d)};O.prototype.screenReaderLabelChanged=function(a){a?this.div.setAttribute("aria-label",a):this.div.removeAttribute("aria-label")};O.prototype.prepareSelection=function(){var a=ff(this.cm,!1);a.focus=ka()==this.div;return a};O.prototype.showSelection=function(a,b){a&&this.cm.display.view.length&&((a.focus||b)&&this.showPrimarySelection(),this.showMultipleSelections(a))};O.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()};O.prototype.showPrimarySelection=function(){var a=this.getSelection(),b=this.cm,d=b.doc.sel.primary(),c=d.from();d=d.to();if(b.display.viewTo==b.display.viewFrom||c.line>=b.display.viewTo||d.line=b.display.viewFrom&&sg(b,c)||{node:e[0].measure.map[2],offset:0},d=d.linea.firstLine()&&(c=t(c.line-1,w(a.doc,c.line-1).length));e.ch==w(a.doc,e.line).text.length&&e.lineb.viewTo-1)return!1;var f;c.line==b.viewFrom||0==(f=bb(a,c.line))?(d=N(b.view[0].line),f=b.view[0].node):(d=N(b.view[f].line),f=b.view[f-1].node.nextSibling);var g=bb(a,e.line);g==b.view.length-1?(e=b.viewTo-1,b=b.lineDiv.lastChild):(e=N(b.view[g+1].line)-1,b=b.view[g+1].node.previousSibling);if(!f)return!1;b=a.doc.splitLines(zh(a,f,b,d,e));for(f=Za(a.doc,t(d,0),t(e,w(a.doc,e).text.length));1c.ch&&k.charCodeAt(k.length-g-1)==l.charCodeAt(l.length-g-1);)h--,g++;b[b.length-1]=k.slice(0,k.length-g).replace(/^\u200b+/,"");b[0]=b[0].slice(h).replace(/\u200b+$/,"");c=t(d,h);d=t(e,f.length?J(f).length-g:0);if(1T&&f.scrollbars.setScrollTop(f.scroller.scrollTop=k),null!=g.selectionStart)){(!G||G&&9>T)&&b();var q=0,r=function(){f.selForContextMenu==e.doc.sel&&0==g.selectionStart&&0q++?f.detectingSelectAll=setTimeout(r,500):(f.selForContextMenu=null,f.input.reset())};f.detectingSelectAll=setTimeout(r,200)}}var c=this,e=c.cm,f=e.display,g=c.textarea;c.contextMenuPending&&c.contextMenuPending();var h=eb(e,a),k=f.scroller.scrollTop;if(h&&!Aa){e.options.resetSelectionOnContextMenu&&-1==e.doc.sel.contains(h)&&ba(e,da)(e.doc,Na(h),Ha);var l=g.style.cssText,m=c.wrapper.style.cssText;h=c.wrapper.offsetParent.getBoundingClientRect();c.wrapper.style.cssText="position: static";g.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(a.clientY-h.top-5)+"px; left: "+(a.clientX-h.left-5)+"px;\n z-index: 1000; background: "+(G?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(fa)var n=window.scrollY;f.input.focus();fa&&window.scrollTo(null,n);f.input.reset();e.somethingSelected()||(g.value=c.prevInput=" ");c.contextMenuPending=d;f.selForContextMenu=e.doc.sel;clearTimeout(f.detectingSelectAll);G&&9<=T&&b();if(ie){Kb(a);var p=function(){sa(window,"mouseup",p);setTimeout(d,20)};z(window,"mouseup",p)}else setTimeout(d,50)}};V.prototype.readOnlyChanged=function(a){a||this.reset();this.textarea.disabled="nocursor"==a;this.textarea.readOnly=!!a};V.prototype.setUneditable=function(){};V.prototype.needsContentAttribute=!1;(function(a){function b(c,e,f,g){a.defaults[c]=e;f&&(d[c]=g?function(h,k,l){l!=Fb&&f(h,k,l)}:f)}var d=a.optionHandlers;a.defineOption=b;a.Init=Fb;b("value","",(function(c,e){return c.setValue(e)}),!0);b("mode",null,(function(c,e){c.doc.modeOption=e;Zd(c)}),!0);b("indentUnit",2,Zd,!0);b("indentWithTabs",!1);b("smartIndent",!0);b("tabSize",4,(function(c){$b(c);Sb(c);ma(c)}),!0);b("lineSeparator",null,(function(c,e){if(c.doc.lineSep=e){var f=[],g=c.doc.first;c.doc.iter((function(k){for(var l=0;;){var m=k.text.indexOf(e,l);if(-1==m)break;l=m+e.length;f.push(t(g,m))}g++}));for(var h=f.length-1;0<=h;h--)Bb(c.doc,e,f[h],t(f[h].line,f[h].ch+e.length))}}));b("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,(function(c,e,f){c.state.specialChars=new RegExp(e.source+(e.test("\t")?"":"|\t"),"g");f!=Fb&&c.refresh()}));b("specialCharPlaceholder",Kg,(function(c){return c.refresh()}),!0);b("electricChars",!0);b("inputStyle",Zb?"contenteditable":"textarea",(function(){throw Error("inputStyle can not (yet) be changed in a running editor")}),!0);b("spellcheck",!1,(function(c,e){return c.getInputField().spellcheck=e}),!0);b("autocorrect",!1,(function(c,e){return c.getInputField().autocorrect=e}),!0);b("autocapitalize",!1,(function(c,e){return c.getInputField().autocapitalize=e}),!0);b("rtlMoveVisually",!Dh);b("wholeLineUpdateBefore",!0);b("theme","default",(function(c){jg(c);Yb(c)}),!0);b("keyMap","default",(function(c,e,f){e=Wc(e);(f=f!=Fb&&Wc(f))&&f.detach&&f.detach(c,e);e.attach&&e.attach(c,f||null)}));b("extraKeys",null);b("configureMouse",null);b("lineWrapping",!1,wh,!0);b("gutters",[],(function(c,e){c.display.gutterSpecs=Xd(e,c.options.lineNumbers);Yb(c)}),!0);b("fixedGutter",!0,(function(c,e){c.display.gutters.style.left=e?Ld(c.display)+"px":"0";c.refresh()}),!0);b("coverGutterNextToScrollbar",!1,(function(c){return wb(c)}),!0);b("scrollbarStyle","native",(function(c){nf(c);wb(c);c.display.scrollbars.setScrollTop(c.doc.scrollTop);c.display.scrollbars.setScrollLeft(c.doc.scrollLeft)}),!0);b("lineNumbers",!1,(function(c,e){c.display.gutterSpecs=Xd(c.options.gutters,e);Yb(c)}),!0);b("firstLineNumber",1,Yb,!0);b("lineNumberFormatter",(function(c){return c}),Yb,!0);b("showCursorWhenSelecting",!1,Tb,!0);b("resetSelectionOnContextMenu",!0);b("lineWiseCopyCut",!0);b("pasteLinesPerSelection",!0);b("selectionsMayTouch",!1);b("readOnly",!1,(function(c,e){"nocursor"==e&&(ub(c),c.display.input.blur());c.display.input.readOnlyChanged(e)}));b("screenReaderLabel",null,(function(c,e){c.display.input.screenReaderLabelChanged(""===e?null:e)}));b("disableInput",!1,(function(c,e){e||c.display.input.reset()}),!0);b("dragDrop",!0,vh);b("allowDropFileTypes",null);b("cursorBlinkRate",530);b("cursorScrollMargin",0);b("cursorHeight",1,Tb,!0);b("singleCursorHeightPerLine",!0,Tb,!0);b("workTime",100);b("workDelay",100);b("flattenSpans",!0,$b,!0);b("addModeClass",!1,$b,!0);b("pollInterval",100);b("undoDepth",200,(function(c,e){return c.doc.history.undoDepth=e}));b("historyEventDelay",1250);b("viewportMargin",10,(function(c){return c.refresh()}),!0);b("maxHighlightLength",1e4,$b,!0);b("moveInputWithCursor",!0,(function(c,e){e||c.display.input.resetPosition()}));b("tabindex",null,(function(c,e){return c.display.input.getField().tabIndex=e||""}));b("autofocus",null);b("direction","ltr",(function(c,e){return c.doc.setDirection(e)}),!0);b("phrases",null)})(U);(function(a){var b=a.optionHandlers,d=a.helpers={};a.prototype={constructor:a,focus:function(){window.focus();this.display.input.focus()},setOption:function(c,e){var f=this.options,g=f[c];if(f[c]!=e||"mode"==c)f[c]=e,b.hasOwnProperty(c)&&ba(this,b[c])(this,e,g),W(this,"optionChange",this,c)},getOption:function(c){return this.options[c]},getDoc:function(){return this.doc},addKeyMap:function(c,e){this.state.keyMaps[e?"push":"unshift"](Wc(c))},removeKeyMap:function(c){for(var e=this.state.keyMaps,f=0;ff&&(lc(this,h.head.line,c,!0),f=h.head.line,g==this.doc.sel.primIndex&&vb(this));else{var k=h.from();h=h.to();var l=Math.max(f,k.line);f=Math.min(this.lastLine(),h.line-(h.ch?0:1))+1;for(h=l;h>1;if((h?e[2*h-1]:0)>=c)g=h;else if(e[2*h+1]f?e:0==f?null:e.slice(0,f-1)},getModeAt:function(c){var e=this.doc.mode;return e.innerMode?a.innerMode(e,this.getTokenAt(c).state).mode:e},getHelper:function(c,e){return this.getHelpers(c,e)[0]},getHelpers:function(c,e){var f=[];if(!d.hasOwnProperty(e))return f;var g=d[e];c=this.getModeAt(c);if("string"==typeof c[e])g[c[e]]&&f.push(g[c[e]]);else if(c[e])for(var h=0;hh&&(c=h,g=!0);c=w(this.doc,c)}return Gc(this,c,{top:0,left:0},e||"page",f||g).top+(g?this.doc.height-Fa(c):0)},defaultTextHeight:function(){return tb(this.display)},defaultCharWidth:function(){return sb(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(c,e,f,g,h){var k=this.display;c=za(this,C(this.doc,c));var l=c.bottom,m=c.left;e.style.position="absolute";e.setAttribute("cm-ignore-events","true");this.display.input.setUneditable(e);k.sizer.appendChild(e);if("over"==g)l=c.top;else if("above"==g||"near"==g){var n=Math.max(k.wrapper.clientHeight,this.doc.height),p=Math.max(k.sizer.clientWidth,k.lineSpace.clientWidth);("above"==g||c.bottom+e.offsetHeight>n)&&c.top>e.offsetHeight?l=c.top-e.offsetHeight:c.bottom+e.offsetHeight<=n&&(l=c.bottom);m+e.offsetWidth>p&&(m=p-e.offsetWidth)}e.style.top=l+"px";e.style.left=e.style.right="";"right"==h?(m=k.sizer.clientWidth-e.offsetWidth,e.style.right="0px"):("left"==h?m=0:"middle"==h&&(m=(k.sizer.clientWidth-e.offsetWidth)/2),e.style.left=m+"px");f&&(c=Sd(this,{left:m,top:l,right:m+e.offsetWidth,bottom:l+e.offsetHeight}),null!=c.scrollTop&&Vb(this,c.scrollTop),null!=c.scrollLeft&&ib(this,c.scrollLeft))},triggerOnKeyDown:ia(dg),triggerOnKeyPress:ia(fg),triggerOnKeyUp:eg,triggerOnMouseDown:ia(gg),execCommand:function(c){if(hc.hasOwnProperty(c))return hc[c].call(null,this)},triggerElectric:ia((function(c){mg(this,c)})),findPosH:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);c=C(this.doc,c);for(var k=0;kc?g.from():g.to()}),oc)})),deleteH:ia((function(c,e){var f=this.doc;this.doc.sel.somethingSelected()?f.replaceSelection("",null,"+delete"):Eb(this,(function(g){var h=ne(f,g.head,c,e,!1);return 0>c?{from:h,to:g.head}:{from:g.head,to:h}}))})),findPosV:function(c,e,f,g){var h=1;0>e&&(h=-1,e=-e);var k=C(this.doc,c);for(c=0;cc?m.from():m.to();var n=za(f,m.head,"div");null!=m.goalColumn&&(n.left=m.goalColumn);h.push(n.left);var p=rg(f,n,c,e);"page"==e&&m==g.sel.primary()&&Mc(f,Hc(f,p,"div").top-n.top);return p}),oc);if(h.length)for(var l=0;lea(Gh,sc)&&(U.prototype[sc]=function(a){return function(){return a.apply(this.doc,arguments)}}(oa.prototype[sc]));nb(oa);U.inputStyles={textarea:V,contenteditable:O};U.defineMode=function(a){U.defaults.mode||"null"==a||(U.defaults.mode=a);Bg.apply(this,arguments)};U.defineMIME=function(a,b){ob[a]=b};U.defineMode("null",(function(){return{token:function(a){return a.skipToEnd()}}}));U.defineMIME("text/plain","null");U.defineExtension=function(a,b){U.prototype[a]=b};U.defineDocExtension=function(a,b){oa.prototype[a]=b};U.fromTextArea=function(a,b){function d(){a.value=h.getValue()}b=b?Xa(b):{};b.value=a.value;!b.tabindex&&a.tabIndex&&(b.tabindex=a.tabIndex);!b.placeholder&&a.placeholder&&(b.placeholder=a.placeholder);if(null==b.autofocus){var c=ka();b.autofocus=c==a||null!=a.getAttribute("autofocus")&&c==document.body}if(a.form&&(z(a.form,"submit",d),!b.leaveSubmitMethodAlone)){var e=a.form;var f=e.submit;try{var g=e.submit=function(){d();e.submit=f;e.submit();e.submit=g}}catch(k){}}b.finishInit=function(k){k.save=d;k.getTextArea=function(){return a};k.toTextArea=function(){k.toTextArea=isNaN;d();a.parentNode.removeChild(k.getWrapperElement());a.style.display="";a.form&&(sa(a.form,"submit",d),b.leaveSubmitMethodAlone||"function"!=typeof a.form.submit||(a.form.submit=f))}};a.style.display="none";var h=U((function(k){return a.parentNode.insertBefore(k,a.nextSibling)}),b);return h};(function(a){a.off=sa;a.on=z;a.wheelEventPixels=Xg;a.Doc=oa;a.splitLines=me;a.countColumn=va;a.findColumn=gd;a.isWordChar=id;a.Pass=Yc;a.signal=W;a.Line=xb;a.changeEnd=Ra;a.scrollbarModel=of;a.Pos=t;a.cmpPos=B;a.modes=ld;a.mimeModes=ob;a.resolveMode=xc;a.getMode=md;a.modeExtensions=pb;a.extendMode=Cg;a.copyState=Ya;a.startState=ve;a.innerMode=nd;a.commands=hc;a.keyMap=gc;a.keyName=Zf;a.isModifierKey=Wf;a.lookupKey=Db;a.normalizeKeyMap=hh;a.StringStream=X;a.SharedTextMarker=fc;a.TextMarker=Ta;a.LineWidget=ec;a.e_preventDefault=la;a.e_stopPropagation=te;a.e_stop=Kb;a.addClass=Wa;a.contains=ja;a.rmClass=hb;a.keyNames=Ua})(U);U.version="5.65.0";return U}))}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],57:[function(require,module,exports){(function(v){"object"==typeof exports&&"object"==typeof module?v(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],v):v(CodeMirror)})((function(v){v.defineMode("javascript",(function(Ua,A){var p,w,f;function u(a,b,d){V=a;ca=d;return b}function I(a,b){var d=a.next();if('"'==d||"'"==d)return b.tokenize=Va(d),b.tokenize(a,b);if("."==d&&a.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return u("number","number");if("."==d&&a.match(".."))return u("spread","meta");if(/[\[\]{}\(\),;:\.]/.test(d))return u(d);if("="==d&&a.eat(">"))return u("=>","operator");if("0"==d&&a.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return u("number","number");if(/\d/.test(d))return a.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),u("number","number");if("/"==d){if(a.eat("*"))return b.tokenize=da,da(a,b);if(a.eat("/"))return a.skipToEnd(),u("comment","comment");if(Aa(a,b,1)){a:for(var e=b=!1;null!=(d=a.next());){if(!b){if("/"==d&&!e)break a;"["==d?e=!0:e&&"]"==d&&(e=!1)}b=!b&&"\\"==d}a.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);return u("regexp","string-2")}a.eat("=");return u("operator","operator",a.current())}if("`"==d)return b.tokenize=W,W(a,b);if("#"==d&&"!"==a.peek())return a.skipToEnd(),u("meta","meta");if("#"==d&&a.eatWhile(ea))return u("variable","property");if("<"==d&&a.match("!--")||"-"==d&&a.match("->")&&!/\S/.test(a.string.slice(0,a.start)))return a.skipToEnd(),u("comment","comment");if(Ba.test(d))return">"==d&&b.lexical&&">"==b.lexical.type||(a.eat("=")?"!"!=d&&"="!=d||a.eat("="):/[<>*+\-|&?]/.test(d)&&(a.eat(d),">"==d&&a.eat(d))),"?"==d&&a.eat(".")?u("."):u("operator","operator",a.current());if(ea.test(d)){a.eatWhile(ea);d=a.current();if("."!=b.lastType){if(Ca.propertyIsEnumerable(d))return a=Ca[d],u(a.type,a.style,d);if("async"==d&&a.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return u("async","keyword",d)}return u("variable","variable",d)}}function Va(a){return function(b,d){var e=!1,h;if(fa&&"@"==b.peek()&&b.match(Wa))return d.tokenize=I,u("jsonld-keyword","meta");for(;null!=(h=b.next())&&(h!=a||e);)e=!e&&"\\"==h;e||(d.tokenize=I);return u("string","string")}}function da(a,b){for(var d=!1,e;e=a.next();){if("/"==e&&d){b.tokenize=I;break}d="*"==e}return u("comment","comment")}function W(a,b){for(var d=!1,e;null!=(e=a.next());){if(!d&&("`"==e||"$"==e&&a.eat("{"))){b.tokenize=I;break}d=!d&&"\\"==e}return u("quasi","string-2",a.current())}function pa(a,b){b.fatArrowAt&&(b.fatArrowAt=null);var d=a.string.indexOf("=>",a.start);if(!(0>d)){if(r){var e=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(a.string.slice(a.start,d));e&&(d=e.index)}e=0;var h=!1;for(--d;0<=d;--d){var m=a.string.charAt(d),y="([{}])".indexOf(m);if(0<=y&&3>y){if(!e){++d;break}if(0==--e){"("==m&&(h=!0);break}}else if(3<=y&&6>y)++e;else if(ea.test(m))h=!0;else if(/["'\/`]/.test(m))for(;;--d){if(0==d)return;if(a.string.charAt(d-1)==m&&"\\"!=a.string.charAt(d-2)){d--;break}}else if(h&&!e){++d;break}}h&&!e&&(b.fatArrowAt=d)}}function Da(a,b,d,e,h,m){this.indented=a;this.column=b;this.type=d;this.prev=h;this.info=m;null!=e&&(this.align=e)}function Ea(a,b,d,e,h){var m=a.cc;p=a;w=h;f=null;qa=m;X=b;a.lexical.hasOwnProperty("align")||(a.lexical.align=!0);for(;;)if((m.length?m.pop():J?t:x)(d,e)){for(;m.length&&m[m.length-1].lex;)m.pop()();if(f)return f;if(d="variable"==d)a:if(Fa){for(d=a.localVars;d;d=d.next)if(d.name==e){d=!0;break a}for(a=a.context;a;a=a.prev)for(d=a.vars;d;d=d.next)if(d.name==e){d=!0;break a}d=void 0}else d=!1;return d?"variable-2":b}}function k(){for(var a=arguments.length-1;0<=a;a--)qa.push(arguments[a])}function c(){k.apply(null,arguments);return!0}function ra(a,b){for(;b;b=b.next)if(b.name==a)return!0;return!1}function N(a){var b=p;f="def";if(Fa){if(b.context)if("var"==b.lexical.info&&b.context&&b.context.block){var d=Ga(a,b.context);if(null!=d){b.context=d;return}}else if(!ra(a,b.localVars)){b.localVars=new Y(a,b.localVars);return}A.globalVars&&!ra(a,b.globalVars)&&(b.globalVars=new Y(a,b.globalVars))}}function Ga(a,b){return b?b.block?(a=Ga(a,b.prev))?a==b.prev?b:new Z(a,b.vars,!0):null:ra(a,b.vars)?b:new Z(b.prev,new Y(a,b.vars),!1):null}function ha(a){return"public"==a||"private"==a||"protected"==a||"abstract"==a||"readonly"==a}function Z(a,b,d){this.prev=a;this.vars=b;this.block=d}function Y(a,b){this.name=a;this.next=b}function O(){p.context=new Z(p.context,p.localVars,!1);p.localVars=Xa}function sa(){p.context=new Z(p.context,p.localVars,!0);p.localVars=null}function C(){p.localVars=p.context.vars;p.context=p.context.prev}function l(a,b){var d=function(){var e=p,h=e.indented;if("stat"==e.lexical.type)h=e.lexical.indented;else for(var m=e.lexical;m&&")"==m.type&&m.align;m=m.prev)h=m.indented;e.lexical=new Da(h,w.column(),a,null,e.lexical,b)};d.lex=!0;return d}function g(){var a=p;a.lexical.prev&&(")"==a.lexical.type&&(a.indented=a.lexical.indented),a.lexical=a.lexical.prev)}function n(a){function b(d){return d==a?c():";"==a||"}"==d||")"==d||"]"==d?k():c(b)}return b}function x(a,b){return"var"==a?c(l("vardef",b),ta,n(";"),g):"keyword a"==a?c(l("form"),ua,x,g):"keyword b"==a?c(l("form"),x,g):"keyword d"==a?w.match(/^\s*$/,!1)?c():c(l("stat"),P,n(";"),g):"debugger"==a?c(n(";")):"{"==a?c(l("}"),sa,ia,g,C):";"==a?c():"if"==a?("else"==p.lexical.info&&p.cc[p.cc.length-1]==g&&p.cc.pop()(),c(l("form"),ua,x,g,Ha)):"function"==a?c(G):"for"==a?c(l("form"),sa,Ia,x,C,g):"class"==a||r&&"interface"==b?(f="keyword",c(l("form","class"==a?a:b),Ja,g)):"variable"==a?r&&"declare"==b?(f="keyword",c(x)):r&&("module"==b||"enum"==b||"type"==b)&&w.match(/^\s*\w/,!1)?(f="keyword","enum"==b?c(Ka):"type"==b?c(La,n("operator"),q,n(";")):c(l("form"),D,n("{"),l("}"),ia,g,g)):r&&"namespace"==b?(f="keyword",c(l("form"),t,x,g)):r&&"abstract"==b?(f="keyword",c(x)):c(l("stat"),Ya):"switch"==a?c(l("form"),ua,n("{"),l("}","switch"),sa,ia,g,g,C):"case"==a?c(t,n(":")):"default"==a?c(n(":")):"catch"==a?c(l("form"),O,Za,x,g,C):"export"==a?c(l("stat"),$a,g):"import"==a?c(l("stat"),ab,g):"async"==a?c(x):"@"==b?c(t,x):k(l("stat"),t,n(";"),g)}function Za(a){if("("==a)return c(K,n(")"))}function t(a,b){return Ma(a,b,!1)}function B(a,b){return Ma(a,b,!0)}function ua(a){return"("!=a?k():c(l(")"),P,n(")"),g)}function Ma(a,b,d){if(p.fatArrowAt==w.start){var e=d?Na:Oa;if("("==a)return c(O,l(")"),z(K,")"),g,n("=>"),e,C);if("variable"==a)return k(O,D,n("=>"),e,C)}e=d?Q:L;return bb.hasOwnProperty(a)?c(e):"function"==a?c(G,e):"class"==a||r&&"interface"==b?(f="keyword",c(l("form"),cb,g)):"keyword c"==a||"async"==a?c(d?B:t):"("==a?c(l(")"),P,n(")"),g,e):"operator"==a||"spread"==a?c(d?B:t):"["==a?c(l("]"),db,g,e):"{"==a?aa(ja,"}",null,e):"quasi"==a?k(ka,e):"new"==a?c(eb(d)):c()}function P(a){return a.match(/[;\}\)\],]/)?k():k(t)}function L(a,b){return","==a?c(P):Q(a,b,!1)}function Q(a,b,d){var e=0==d?L:Q,h=0==d?t:B;if("=>"==a)return c(O,d?Na:Oa,C);if("operator"==a)return/\+\+|--/.test(b)||r&&"!"==b?c(e):r&&"<"==b&&w.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?c(l(">"),z(q,">"),g,e):"?"==b?c(t,n(":"),h):c(h);if("quasi"==a)return k(ka,e);if(";"!=a){if("("==a)return aa(B,")","call",e);if("."==a)return c(fb,e);if("["==a)return c(l("]"),P,n("]"),g,e);if(r&&"as"==b)return f="keyword",c(q,e);if("regexp"==a)return p.lastType=f="operator",w.backUp(w.pos-w.start-1),c(h)}}function ka(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ka):c(P,gb)}function gb(a){if("}"==a)return f="string-2",p.tokenize=W,c(ka)}function Oa(a){pa(w,p);return k("{"==a?x:t)}function Na(a){pa(w,p);return k("{"==a?x:B)}function eb(a){return function(b){return"."==b?c(a?hb:ib):"variable"==b&&r?c(jb,a?Q:L):k(a?B:t)}}function ib(a,b){if("target"==b)return f="keyword",c(L)}function hb(a,b){if("target"==b)return f="keyword",c(Q)}function Ya(a){return":"==a?c(g,x):k(L,n(";"),g)}function fb(a){if("variable"==a)return f="property",c()}function ja(a,b){if("async"==a)return f="property",c(ja);if("variable"==a||"keyword"==X){f="property";if("get"==b||"set"==b)return c(kb);var d;r&&p.fatArrowAt==w.start&&(d=w.match(/^\s*:\s*/,!1))&&(p.fatArrowAt=w.pos+d[0].length);return c(M)}if("number"==a||"string"==a)return f=fa?"property":X+" property",c(M);if("jsonld-keyword"==a)return c(M);if(r&&ha(b))return f="keyword",c(ja);if("["==a)return c(t,R,n("]"),M);if("spread"==a)return c(B,M);if("*"==b)return f="keyword",c(ja);if(":"==a)return k(M)}function kb(a){if("variable"!=a)return k(M);f="property";return c(G)}function M(a){if(":"==a)return c(B);if("("==a)return k(G)}function z(a,b,d){function e(h,m){return(d?-1"),q);if("quasi"==a)return k(ya,E)}function nb(a){if("=>"==a)return c(q)}function wa(a){return a.match(/[\}\)\]]/)?c():","==a||";"==a?c(wa):k(ba,wa)}function ba(a,b){if("variable"==a||"keyword"==X)return f="property",c(ba);if("?"==b||"number"==a||"string"==a)return c(ba);if(":"==a)return c(q);if("["==a)return c(n("variable"),lb,n("]"),ba);if("("==a)return k(S,ba);if(!a.match(/[;\}\)\],]/))return c()}function ya(a,b){return"quasi"!=a?k():"${"!=b.slice(b.length-2)?c(ya):c(q,ob)}function ob(a){if("}"==a)return f="string-2",p.tokenize=W,c(ya)}function xa(a,b){return"variable"==a&&w.match(/^\s*[?:]/,!1)||"?"==b?c(xa):":"==a?c(q):"spread"==a?c(xa):k(q)}function E(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E);if("|"==b||"."==a||"&"==b)return c(q);if("["==a)return c(q,n("]"),E);if("extends"==b||"implements"==b)return f="keyword",c(q);if("?"==b)return c(q,n(":"),q)}function jb(a,b){if("<"==b)return c(l(">"),z(q,">"),g,E)}function la(){return k(q,pb)}function pb(a,b){if("="==b)return c(q)}function ta(a,b){return"enum"==b?(f="keyword",c(Ka)):k(D,R,H,qb)}function D(a,b){if(r&&ha(b))return f="keyword",c(D);if("variable"==a)return N(b),c();if("spread"==a)return c(D);if("["==a)return aa(rb,"]");if("{"==a)return aa(Qa,"}")}function Qa(a,b){if("variable"==a&&!w.match(/^\s*:/,!1))return N(b),c(H);"variable"==a&&(f="property");return"spread"==a?c(D):"}"==a?k():"["==a?c(t,n("]"),n(":"),Qa):c(n(":"),D,H)}function rb(){return k(D,H)}function H(a,b){if("="==b)return c(B)}function qb(a){if(","==a)return c(ta)}function Ha(a,b){if("keyword b"==a&&"else"==b)return c(l("form","else"),x,g)}function Ia(a,b){if("await"==b)return c(Ia);if("("==a)return c(l(")"),sb,g)}function sb(a){return"var"==a?c(ta,T):"variable"==a?c(T):k(T)}function T(a,b){return")"==a?c():";"==a?c(T):"in"==b||"of"==b?(f="keyword",c(t,T)):k(t,T)}function G(a,b){if("*"==b)return f="keyword",c(G);if("variable"==a)return N(b),c(G);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,x,C);if(r&&"<"==b)return c(l(">"),z(la,">"),g,G)}function S(a,b){if("*"==b)return f="keyword",c(S);if("variable"==a)return N(b),c(S);if("("==a)return c(O,l(")"),z(K,")"),g,Pa,C);if(r&&"<"==b)return c(l(">"),z(la,">"),g,S)}function La(a,b){if("keyword"==a||"variable"==a)return f="type",c(La);if("<"==b)return c(l(">"),z(la,">"),g)}function K(a,b){"@"==b&&c(t,K);return"spread"==a?c(K):r&&ha(b)?(f="keyword",c(K)):r&&"this"==a?c(R,H):k(D,R,H)}function cb(a,b){return"variable"==a?Ja(a,b):ma(a,b)}function Ja(a,b){if("variable"==a)return N(b),c(ma)}function ma(a,b){if("<"==b)return c(l(">"),z(la,">"),g,ma);if("extends"==b||"implements"==b||r&&","==a)return"implements"==b&&(f="keyword"),c(r?q:t,ma);if("{"==a)return c(l("}"),F,g)}function F(a,b){if("async"==a||"variable"==a&&("static"==b||"get"==b||"set"==b||r&&ha(b))&&w.match(/^\s+[\w$\xa1-\uffff]/,!1))return f="keyword",c(F);if("variable"==a||"keyword"==X)return f="property",c(na,F);if("number"==a||"string"==a)return c(na,F);if("["==a)return c(t,R,n("]"),na,F);if("*"==b)return f="keyword",c(F);if(r&&"("==a)return k(S,F);if(";"==a||","==a)return c(F);if("}"==a)return c();if("@"==b)return c(t,F)}function na(a,b){if("!"==b||"?"==b)return c(na);if(":"==a)return c(q,H);if("="==b)return c(B);a=p.lexical.prev;return k(a&&"interface"==a.info?S:G)}function $a(a,b){return"*"==b?(f="keyword",c(za,n(";"))):"default"==b?(f="keyword",c(t,n(";"))):"{"==a?c(z(Ra,"}"),za,n(";")):k(x)}function Ra(a,b){if("as"==b)return f="keyword",c(n("variable"));if("variable"==a)return k(B,Ra)}function ab(a){return"string"==a?c():"("==a?k(t):"."==a?k(L):k(oa,Sa,za)}function oa(a,b){if("{"==a)return aa(oa,"}");"variable"==a&&N(b);"*"==b&&(f="keyword");return c(tb)}function Sa(a){if(","==a)return c(oa,Sa)}function tb(a,b){if("as"==b)return f="keyword",c(oa)}function za(a,b){if("from"==b)return f="keyword",c(t)}function db(a){return"]"==a?c():k(z(B,"]"))}function Ka(){return k(l("form"),D,n("{"),l("}"),z(ub,"}"),g,g)}function ub(){return k(D,H)}function Aa(a,b,d){return b.tokenize==I&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(b.lastType)||"quasi"==b.lastType&&/\{\s*$/.test(a.string.slice(0,a.pos-(d||0)))}var U=Ua.indentUnit,Ta=A.statementIndent,fa=A.jsonld,J=A.json||fa,Fa=!1!==A.trackScope,r=A.typescript,ea=A.wordCharacters||/[\w$\xa1-\uffff]/,Ca=function(){function a(va){return{type:va,style:"keyword"}}var b=a("keyword a"),d=a("keyword b"),e=a("keyword c"),h=a("keyword d"),m=a("operator"),y={type:"atom",style:"atom"};return{if:a("if"),while:b,with:b,else:d,do:d,try:d,finally:d,return:h,break:h,continue:h,new:a("new"),delete:e,void:e,throw:e,debugger:a("debugger"),var:a("var"),const:a("var"),let:a("var"),function:a("function"),catch:a("catch"),for:a("for"),switch:a("switch"),case:a("case"),default:a("default"),in:m,typeof:m,instanceof:m,true:y,false:y,null:y,undefined:y,NaN:y,Infinity:y,this:a("this"),class:a("class"),super:a("atom"),yield:e,export:a("export"),import:a("import"),extends:e,await:e}}(),Ba=/[+\-*&%=<>!?|~^@]/,Wa=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,V,ca,bb={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,import:!0,"jsonld-keyword":!0};var qa=f=p=null;var X=w=void 0;var Xa=new Y("this",new Y("arguments",null));C.lex=!0;g.lex=!0;return{startState:function(a){a={tokenize:I,lastType:"sof",cc:[],lexical:new Da((a||0)-U,0,"block",!1),localVars:A.localVars,context:A.localVars&&new Z(null,null,!1),indented:a||0};A.globalVars&&"object"==typeof A.globalVars&&(a.globalVars=A.globalVars);return a},token:function(a,b){a.sol()&&(b.lexical.hasOwnProperty("align")||(b.lexical.align=!1),b.indented=a.indentation(),pa(a,b));if(b.tokenize!=da&&a.eatSpace())return null;var d=b.tokenize(a,b);if("comment"==V)return d;b.lastType="operator"!=V||"++"!=ca&&"--"!=ca?V:"incdec";return Ea(b,d,V,ca,a)},indent:function(a,b){if(a.tokenize==da||a.tokenize==W)return v.Pass;if(a.tokenize!=I)return 0;var d=b&&b.charAt(0),e=a.lexical,h;if(!/^\s*else\b/.test(b))for(var m=a.cc.length-1;0<=m;--m){var y=a.cc[m];if(y==g)e=e.prev;else if(y!=Ha&&y!=C)break}for(;!("stat"!=e.type&&"form"!=e.type||"}"!=d&&(!(h=a.cc[a.cc.length-1])||h!=L&&h!=Q||/^[,\.=+\-*:?[\(]/.test(b)));)e=e.prev;Ta&&")"==e.type&&"stat"==e.prev.type&&(e=e.prev);h=e.type;m=d==h;return"vardef"==h?e.indented+("operator"==a.lastType||","==a.lastType?e.info.length+1:0):"form"==h&&"{"==d?e.indented:"form"==h?e.indented+U:"stat"==h?(d=e.indented,a="operator"==a.lastType||","==a.lastType||Ba.test(b.charAt(0))||/[,.]/.test(b.charAt(0)),d+(a?Ta||U:0)):"switch"!=e.info||m||0==A.doubleIndentSwitch?e.align?e.column+(m?0:1):e.indented+(m?0:U):e.indented+(/^(?:case|default)\b/.test(b)?U:2*U)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:J?null:"/*",blockCommentEnd:J?null:"*/",blockCommentContinue:J?null:" * ",lineComment:J?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:J?"json":"javascript",jsonldMode:fa,jsonMode:J,expressionAllowed:Aa,skipExpression:function(a){Ea(a,"atom","atom","true",new v.StringStream("",2,null))}}}));v.registerHelper("wordChars","javascript",/[\w$]/);v.defineMIME("text/javascript","javascript");v.defineMIME("text/ecmascript","javascript");v.defineMIME("application/javascript","javascript");v.defineMIME("application/x-javascript","javascript");v.defineMIME("application/ecmascript","javascript");v.defineMIME("application/json",{name:"javascript",json:!0});v.defineMIME("application/x-json",{name:"javascript",json:!0});v.defineMIME("application/manifest+json",{name:"javascript",json:!0});v.defineMIME("application/ld+json",{name:"javascript",jsonld:!0});v.defineMIME("text/typescript",{name:"javascript",typescript:!0});v.defineMIME("application/typescript",{name:"javascript",typescript:!0})}))},{"../../lib/codemirror":56}],58:[function(require,module,exports){if(typeof module!=="undefined"){module.exports=Emitter}function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks["$"+event]=this._callbacks["$"+event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){function on(){this.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks["$"+event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks["$"+event];return this}var cb;for(var i=0;i{if(typeof self!=="undefined"){return self}else if(typeof window!=="undefined"){return window}else{return Function("return this")()}})()},{}],61:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.installTimerFunctions=exports.transports=exports.Transport=exports.protocol=exports.Socket=void 0;const socket_js_1=require("./socket.js");Object.defineProperty(exports,"Socket",{enumerable:true,get:function(){return socket_js_1.Socket}});exports.protocol=socket_js_1.Socket.protocol;var transport_js_1=require("./transport.js");Object.defineProperty(exports,"Transport",{enumerable:true,get:function(){return transport_js_1.Transport}});var index_js_1=require("./transports/index.js");Object.defineProperty(exports,"transports",{enumerable:true,get:function(){return index_js_1.transports}});var util_js_1=require("./util.js");Object.defineProperty(exports,"installTimerFunctions",{enumerable:true,get:function(){return util_js_1.installTimerFunctions}})},{"./socket.js":62,"./transport.js":63,"./transports/index.js":64,"./util.js":70}],62:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.Socket=void 0;const index_js_1=require("./transports/index.js");const util_js_1=require("./util.js");const parseqs_1=__importDefault(require("parseqs"));const parseuri_1=__importDefault(require("parseuri"));const debug_1=__importDefault(require("debug"));const component_emitter_1=require("@socket.io/component-emitter");const engine_io_parser_1=require("engine.io-parser");const debug=(0,debug_1.default)("engine.io-client:socket");class Socket extends component_emitter_1.Emitter{constructor(uri,opts={}){super();if(uri&&"object"===typeof uri){opts=uri;uri=null}if(uri){uri=(0,parseuri_1.default)(uri);opts.hostname=uri.host;opts.secure=uri.protocol==="https"||uri.protocol==="wss";opts.port=uri.port;if(uri.query)opts.query=uri.query}else if(opts.host){opts.hostname=(0,parseuri_1.default)(opts.host).host}(0,util_js_1.installTimerFunctions)(this,opts);this.secure=null!=opts.secure?opts.secure:typeof location!=="undefined"&&"https:"===location.protocol;if(opts.hostname&&!opts.port){opts.port=this.secure?"443":"80"}this.hostname=opts.hostname||(typeof location!=="undefined"?location.hostname:"localhost");this.port=opts.port||(typeof location!=="undefined"&&location.port?location.port:this.secure?"443":"80");this.transports=opts.transports||["polling","websocket"];this.readyState="";this.writeBuffer=[];this.prevBufferLen=0;this.opts=Object.assign({path:"/engine.io",agent:false,withCredentials:false,upgrade:true,timestampParam:"t",rememberUpgrade:false,rejectUnauthorized:true,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:true},opts);this.opts.path=this.opts.path.replace(/\/$/,"")+"/";if(typeof this.opts.query==="string"){this.opts.query=parseqs_1.default.decode(this.opts.query)}this.id=null;this.upgrades=null;this.pingInterval=null;this.pingTimeout=null;this.pingTimeoutTimer=null;if(typeof addEventListener==="function"){if(this.opts.closeOnBeforeunload){addEventListener("beforeunload",(()=>{if(this.transport){this.transport.removeAllListeners();this.transport.close()}}),false)}if(this.hostname!=="localhost"){this.offlineEventListener=()=>{this.onClose("transport close")};addEventListener("offline",this.offlineEventListener,false)}}this.open()}createTransport(name){debug('creating transport "%s"',name);const query=clone(this.opts.query);query.EIO=engine_io_parser_1.protocol;query.transport=name;if(this.id)query.sid=this.id;const opts=Object.assign({},this.opts.transportOptions[name],this.opts,{query:query,socket:this,hostname:this.hostname,secure:this.secure,port:this.port});debug("options: %j",opts);return new index_js_1.transports[name](opts)}open(){let transport;if(this.opts.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1){transport="websocket"}else if(0===this.transports.length){this.setTimeoutFn((()=>{this.emitReserved("error","No transports available")}),0);return}else{transport=this.transports[0]}this.readyState="opening";try{transport=this.createTransport(transport)}catch(e){debug("error while creating transport: %s",e);this.transports.shift();this.open();return}transport.open();this.setTransport(transport)}setTransport(transport){debug("setting transport %s",transport.name);if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",this.onDrain.bind(this)).on("packet",this.onPacket.bind(this)).on("error",this.onError.bind(this)).on("close",(()=>{this.onClose("transport close")}))}probe(name){debug('probing transport "%s"',name);let transport=this.createTransport(name);let failed=false;Socket.priorWebsocketSuccess=false;const onTransportOpen=()=>{if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",(msg=>{if(failed)return;if("pong"===msg.type&&"probe"===msg.data){debug('probe transport "%s" pong',name);this.upgrading=true;this.emitReserved("upgrading",transport);if(!transport)return;Socket.priorWebsocketSuccess="websocket"===transport.name;debug('pausing current transport "%s"',this.transport.name);this.transport.pause((()=>{if(failed)return;if("closed"===this.readyState)return;debug("changing transport and sending upgrade packet");cleanup();this.setTransport(transport);transport.send([{type:"upgrade"}]);this.emitReserved("upgrade",transport);transport=null;this.upgrading=false;this.flush()}))}else{debug('probe transport "%s" failed',name);const err=new Error("probe error");err.transport=transport.name;this.emitReserved("upgradeError",err)}}))};function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}const onerror=err=>{const error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);this.emitReserved("upgradeError",error)};function onTransportClose(){onerror("transport closed")}function onclose(){onerror("socket closed")}function onupgrade(to){if(transport&&to.name!==transport.name){debug('"%s" works - aborting "%s"',to.name,transport.name);freezeTransport()}}const cleanup=()=>{transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);this.off("close",onclose);this.off("upgrading",onupgrade)};transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()}onOpen(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"===this.transport.name;this.emitReserved("open");this.flush();if("open"===this.readyState&&this.opts.upgrade&&this.transport.pause){debug("starting upgrade probes");let i=0;const l=this.upgrades.length;for(;i{this.onClose("ping timeout")}),this.pingInterval+this.pingTimeout);if(this.opts.autoUnref){this.pingTimeoutTimer.unref()}}onDrain(){this.writeBuffer.splice(0,this.prevBufferLen);this.prevBufferLen=0;if(0===this.writeBuffer.length){this.emitReserved("drain")}else{this.flush()}}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){debug("flushing %d packets in socket",this.writeBuffer.length);this.transport.send(this.writeBuffer);this.prevBufferLen=this.writeBuffer.length;this.emitReserved("flush")}}write(msg,options,fn){this.sendPacket("message",msg,options,fn);return this}send(msg,options,fn){this.sendPacket("message",msg,options,fn);return this}sendPacket(type,data,options,fn){if("function"===typeof data){fn=data;data=undefined}if("function"===typeof options){fn=options;options=null}if("closing"===this.readyState||"closed"===this.readyState){return}options=options||{};options.compress=false!==options.compress;const packet={type:type,data:data,options:options};this.emitReserved("packetCreate",packet);this.writeBuffer.push(packet);if(fn)this.once("flush",fn);this.flush()}close(){const close=()=>{this.onClose("forced close");debug("socket closing - telling transport to close");this.transport.close()};const cleanupAndClose=()=>{this.off("upgrade",cleanupAndClose);this.off("upgradeError",cleanupAndClose);close()};const waitForUpgrade=()=>{this.once("upgrade",cleanupAndClose);this.once("upgradeError",cleanupAndClose)};if("opening"===this.readyState||"open"===this.readyState){this.readyState="closing";if(this.writeBuffer.length){this.once("drain",(()=>{if(this.upgrading){waitForUpgrade()}else{close()}}))}else if(this.upgrading){waitForUpgrade()}else{close()}}return this}onError(err){debug("socket error %j",err);Socket.priorWebsocketSuccess=false;this.emitReserved("error",err);this.onClose("transport error",err)}onClose(reason,desc){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){debug('socket close with reason: "%s"',reason);this.clearTimeoutFn(this.pingTimeoutTimer);this.transport.removeAllListeners("close");this.transport.close();this.transport.removeAllListeners();if(typeof removeEventListener==="function"){removeEventListener("offline",this.offlineEventListener,false)}this.readyState="closed";this.id=null;this.emitReserved("close",reason,desc);this.writeBuffer=[];this.prevBufferLen=0}}filterUpgrades(upgrades){const filteredUpgrades=[];let i=0;const j=upgrades.length;for(;i{this.onError("xhr post error",err)}))}doPoll(){debug("xhr poll");const req=this.request();req.on("data",this.onData.bind(this));req.on("error",(err=>{this.onError("xhr poll error",err)}));this.pollXhr=req}}exports.XHR=XHR;class Request extends component_emitter_1.Emitter{constructor(uri,opts){super();(0,util_js_1.installTimerFunctions)(this,opts);this.opts=opts;this.method=opts.method||"GET";this.uri=uri;this.async=false!==opts.async;this.data=undefined!==opts.data?opts.data:null;this.create()}create(){const opts=(0,util_js_1.pick)(this.opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");opts.xdomain=!!this.opts.xd;opts.xscheme=!!this.opts.xs;const xhr=this.xhr=new xmlhttprequest_js_1.default(opts);try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);try{if(this.opts.extraHeaders){xhr.setDisableHeaderCheck&&xhr.setDisableHeaderCheck(true);for(let i in this.opts.extraHeaders){if(this.opts.extraHeaders.hasOwnProperty(i)){xhr.setRequestHeader(i,this.opts.extraHeaders[i])}}}}catch(e){}if("POST"===this.method){try{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(e){}}try{xhr.setRequestHeader("Accept","*/*")}catch(e){}if("withCredentials"in xhr){xhr.withCredentials=this.opts.withCredentials}if(this.opts.requestTimeout){xhr.timeout=this.opts.requestTimeout}xhr.onreadystatechange=()=>{if(4!==xhr.readyState)return;if(200===xhr.status||1223===xhr.status){this.onLoad()}else{this.setTimeoutFn((()=>{this.onError(typeof xhr.status==="number"?xhr.status:0)}),0)}};debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){this.setTimeoutFn((()=>{this.onError(e)}),0);return}if(typeof document!=="undefined"){this.index=Request.requestsCount++;Request.requests[this.index]=this}}onSuccess(){this.emit("success");this.cleanup()}onData(data){this.emit("data",data);this.onSuccess()}onError(err){this.emit("error",err);this.cleanup(true)}cleanup(fromError){if("undefined"===typeof this.xhr||null===this.xhr){return}this.xhr.onreadystatechange=empty;if(fromError){try{this.xhr.abort()}catch(e){}}if(typeof document!=="undefined"){delete Request.requests[this.index]}this.xhr=null}onLoad(){const data=this.xhr.responseText;if(data!==null){this.onData(data)}}abort(){this.cleanup()}}exports.Request=Request;Request.requestsCount=0;Request.requests={};if(typeof document!=="undefined"){if(typeof attachEvent==="function"){attachEvent("onunload",unloadHandler)}else if(typeof addEventListener==="function"){const terminationEvent="onpagehide"in globalThis_js_1.default?"pagehide":"unload";addEventListener(terminationEvent,unloadHandler,false)}}function unloadHandler(){for(let i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}},{"../globalThis.js":60,"../util.js":70,"./polling.js":66,"./xmlhttprequest.js":69,"@socket.io/component-emitter":17,debug:71}],66:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.Polling=void 0;const transport_js_1=require("../transport.js");const debug_1=__importDefault(require("debug"));const yeast_1=__importDefault(require("yeast"));const parseqs_1=__importDefault(require("parseqs"));const engine_io_parser_1=require("engine.io-parser");const debug=(0,debug_1.default)("engine.io-client:polling");class Polling extends transport_js_1.Transport{constructor(){super(...arguments);this.polling=false}get name(){return"polling"}doOpen(){this.poll()}pause(onPause){this.readyState="pausing";const pause=()=>{debug("paused");this.readyState="paused";onPause()};if(this.polling||!this.writable){let total=0;if(this.polling){debug("we are currently polling - waiting to pause");total++;this.once("pollComplete",(function(){debug("pre-pause polling complete");--total||pause()}))}if(!this.writable){debug("we are currently writing - waiting to pause");total++;this.once("drain",(function(){debug("pre-pause writing complete");--total||pause()}))}}else{pause()}}poll(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")}onData(data){debug("polling got data %s",data);const callback=packet=>{if("opening"===this.readyState&&packet.type==="open"){this.onOpen()}if("close"===packet.type){this.onClose();return false}this.onPacket(packet)};(0,engine_io_parser_1.decodePayload)(data,this.socket.binaryType).forEach(callback);if("closed"!==this.readyState){this.polling=false;this.emit("pollComplete");if("open"===this.readyState){this.poll()}else{debug('ignoring poll - transport state "%s"',this.readyState)}}}doClose(){const close=()=>{debug("writing close packet");this.write([{type:"close"}])};if("open"===this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}}write(packets){this.writable=false;(0,engine_io_parser_1.encodePayload)(packets,(data=>{this.doWrite(data,(()=>{this.writable=true;this.emit("drain")}))}))}uri(){let query=this.query||{};const schema=this.opts.secure?"https":"http";let port="";if(false!==this.opts.timestampRequests){query[this.opts.timestampParam]=(0,yeast_1.default)()}if(!this.supportsBinary&&!query.sid){query.b64=1}if(this.opts.port&&("https"===schema&&Number(this.opts.port)!==443||"http"===schema&&Number(this.opts.port)!==80)){port=":"+this.opts.port}const encodedQuery=parseqs_1.default.encode(query);const ipv6=this.opts.hostname.indexOf(":")!==-1;return schema+"://"+(ipv6?"["+this.opts.hostname+"]":this.opts.hostname)+port+this.opts.path+(encodedQuery.length?"?"+encodedQuery:"")}}exports.Polling=Polling},{"../transport.js":63,debug:71,"engine.io-parser":77,parseqs:169,yeast:241}],67:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.defaultBinaryType=exports.usingBrowserWebSocket=exports.WebSocket=exports.nextTick=void 0;const globalThis_js_1=__importDefault(require("../globalThis.js"));exports.nextTick=(()=>{const isPromiseAvailable=typeof Promise==="function"&&typeof Promise.resolve==="function";if(isPromiseAvailable){return cb=>Promise.resolve().then(cb)}else{return(cb,setTimeoutFn)=>setTimeoutFn(cb,0)}})();exports.WebSocket=globalThis_js_1.default.WebSocket||globalThis_js_1.default.MozWebSocket;exports.usingBrowserWebSocket=true;exports.defaultBinaryType="arraybuffer"},{"../globalThis.js":60}],68:[function(require,module,exports){(function(Buffer){(function(){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.WS=void 0;const transport_js_1=require("../transport.js");const parseqs_1=__importDefault(require("parseqs"));const yeast_1=__importDefault(require("yeast"));const util_js_1=require("../util.js");const websocket_constructor_js_1=require("./websocket-constructor.js");const debug_1=__importDefault(require("debug"));const engine_io_parser_1=require("engine.io-parser");const debug=(0,debug_1.default)("engine.io-client:websocket");const isReactNative=typeof navigator!=="undefined"&&typeof navigator.product==="string"&&navigator.product.toLowerCase()==="reactnative";class WS extends transport_js_1.Transport{constructor(opts){super(opts);this.supportsBinary=!opts.forceBase64}get name(){return"websocket"}doOpen(){if(!this.check()){return}const uri=this.uri();const protocols=this.opts.protocols;const opts=isReactNative?{}:(0,util_js_1.pick)(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");if(this.opts.extraHeaders){opts.headers=this.opts.extraHeaders}try{this.ws=websocket_constructor_js_1.usingBrowserWebSocket&&!isReactNative?protocols?new websocket_constructor_js_1.WebSocket(uri,protocols):new websocket_constructor_js_1.WebSocket(uri):new websocket_constructor_js_1.WebSocket(uri,protocols,opts)}catch(err){return this.emit("error",err)}this.ws.binaryType=this.socket.binaryType||websocket_constructor_js_1.defaultBinaryType;this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{if(this.opts.autoUnref){this.ws._socket.unref()}this.onOpen()};this.ws.onclose=this.onClose.bind(this);this.ws.onmessage=ev=>this.onData(ev.data);this.ws.onerror=e=>this.onError("websocket error",e)}write(packets){this.writable=false;for(let i=0;i{const opts={};if(!websocket_constructor_js_1.usingBrowserWebSocket){if(packet.options){opts.compress=packet.options.compress}if(this.opts.perMessageDeflate){const len="string"===typeof data?Buffer.byteLength(data):data.length;if(len{this.writable=true;this.emit("drain")}),this.setTimeoutFn)}}))}}doClose(){if(typeof this.ws!=="undefined"){this.ws.close();this.ws=null}}uri(){let query=this.query||{};const schema=this.opts.secure?"wss":"ws";let port="";if(this.opts.port&&("wss"===schema&&Number(this.opts.port)!==443||"ws"===schema&&Number(this.opts.port)!==80)){port=":"+this.opts.port}if(this.opts.timestampRequests){query[this.opts.timestampParam]=(0,yeast_1.default)()}if(!this.supportsBinary){query.b64=1}const encodedQuery=parseqs_1.default.encode(query);const ipv6=this.opts.hostname.indexOf(":")!==-1;return schema+"://"+(ipv6?"["+this.opts.hostname+"]":this.opts.hostname)+port+this.opts.path+(encodedQuery.length?"?"+encodedQuery:"")}check(){return!!websocket_constructor_js_1.WebSocket&&!("__initialize"in websocket_constructor_js_1.WebSocket&&this.name===WS.prototype.name)}}exports.WS=WS}).call(this)}).call(this,require("buffer").Buffer)},{"../transport.js":63,"../util.js":70,"./websocket-constructor.js":67,buffer:32,debug:71,"engine.io-parser":77,parseqs:169,yeast:241}],69:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});const has_cors_1=__importDefault(require("has-cors"));const globalThis_js_1=__importDefault(require("../globalThis.js"));function default_1(opts){const xdomain=opts.xdomain;try{if("undefined"!==typeof XMLHttpRequest&&(!xdomain||has_cors_1.default)){return new XMLHttpRequest}}catch(e){}if(!xdomain){try{return new(globalThis_js_1.default[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(e){}}}exports.default=default_1},{"../globalThis.js":60,"has-cors":86}],70:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.installTimerFunctions=exports.pick=void 0;const globalThis_js_1=__importDefault(require("./globalThis.js"));function pick(obj,...attr){return attr.reduce(((acc,k)=>{if(obj.hasOwnProperty(k)){acc[k]=obj[k]}return acc}),{})}exports.pick=pick;const NATIVE_SET_TIMEOUT=setTimeout;const NATIVE_CLEAR_TIMEOUT=clearTimeout;function installTimerFunctions(obj,opts){if(opts.useNativeTimers){obj.setTimeoutFn=NATIVE_SET_TIMEOUT.bind(globalThis_js_1.default);obj.clearTimeoutFn=NATIVE_CLEAR_TIMEOUT.bind(globalThis_js_1.default)}else{obj.setTimeoutFn=setTimeout.bind(globalThis_js_1.default);obj.clearTimeoutFn=clearTimeout.bind(globalThis_js_1.default)}}exports.installTimerFunctions=installTimerFunctions},{"./globalThis.js":60}],71:[function(require,module,exports){(function(process){(function(){exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=localstorage();exports.destroy=(()=>{let warned=false;return()=>{if(!warned){warned=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(args){args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff);if(!this.useColors){return}const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0;let lastC=0;args[0].replace(/%[a-zA-Z%]/g,(match=>{if(match==="%%"){return}index++;if(match==="%c"){lastC=index}}));args.splice(lastC,0,c)}exports.log=console.debug||console.log||(()=>{});function save(namespaces){try{if(namespaces){exports.storage.setItem("debug",namespaces)}else{exports.storage.removeItem("debug")}}catch(error){}}function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}function localstorage(){try{return localStorage}catch(error){}}module.exports=require("./common")(exports);const{formatters:formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":72,_process:174}],72:[function(require,module,exports){function setup(env){createDebug.debug=createDebug;createDebug.default=createDebug;createDebug.coerce=coerce;createDebug.disable=disable;createDebug.enable=enable;createDebug.enabled=enabled;createDebug.humanize=require("ms");createDebug.destroy=destroy;Object.keys(env).forEach((key=>{createDebug[key]=env[key]}));createDebug.names=[];createDebug.skips=[];createDebug.formatters={};function selectColor(namespace){let hash=0;for(let i=0;i{if(match==="%%"){return"%"}index++;const formatter=createDebug.formatters[format];if(typeof formatter==="function"){const val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match}));createDebug.formatArgs.call(self,args);const logFn=self.log||createDebug.log;logFn.apply(self,args)}debug.namespace=namespace;debug.useColors=createDebug.useColors();debug.color=createDebug.selectColor(namespace);debug.extend=extend;debug.destroy=createDebug.destroy;Object.defineProperty(debug,"enabled",{enumerable:true,configurable:false,get:()=>{if(enableOverride!==null){return enableOverride}if(namespacesCache!==createDebug.namespaces){namespacesCache=createDebug.namespaces;enabledCache=createDebug.enabled(namespace)}return enabledCache},set:v=>{enableOverride=v}});if(typeof createDebug.init==="function"){createDebug.init(debug)}return debug}function extend(namespace,delimiter){const newDebug=createDebug(this.namespace+(typeof delimiter==="undefined"?":":delimiter)+namespace);newDebug.log=this.log;return newDebug}function enable(namespaces){createDebug.save(namespaces);createDebug.namespaces=namespaces;createDebug.names=[];createDebug.skips=[];let i;const split=(typeof namespaces==="string"?namespaces:"").split(/[\s,]+/);const len=split.length;for(i=0;i"-"+namespace))].join(",");createDebug.enable("");return namespaces}function enabled(name){if(name[name.length-1]==="*"){return true}let i;let len;for(i=0,len=createDebug.skips.length;i0){return parse(val)}else if(type==="number"&&isFinite(val)){return options.long?fmtLong(val):fmtShort(val)}throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse(str){str=String(str);if(str.length>100){return}var match=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str);if(!match){return}var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"weeks":case"week":case"w":return n*w;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return undefined}}function fmtShort(ms){var msAbs=Math.abs(ms);if(msAbs>=d){return Math.round(ms/d)+"d"}if(msAbs>=h){return Math.round(ms/h)+"h"}if(msAbs>=m){return Math.round(ms/m)+"m"}if(msAbs>=s){return Math.round(ms/s)+"s"}return ms+"ms"}function fmtLong(ms){var msAbs=Math.abs(ms);if(msAbs>=d){return plural(ms,msAbs,d,"day")}if(msAbs>=h){return plural(ms,msAbs,h,"hour")}if(msAbs>=m){return plural(ms,msAbs,m,"minute")}if(msAbs>=s){return plural(ms,msAbs,s,"second")}return ms+" ms"}function plural(ms,msAbs,n,name){var isPlural=msAbs>=n*1.5;return Math.round(ms/n)+" "+name+(isPlural?"s":"")}},{}],74:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ERROR_PACKET=exports.PACKET_TYPES_REVERSE=exports.PACKET_TYPES=void 0;const PACKET_TYPES=Object.create(null);exports.PACKET_TYPES=PACKET_TYPES;PACKET_TYPES["open"]="0";PACKET_TYPES["close"]="1";PACKET_TYPES["ping"]="2";PACKET_TYPES["pong"]="3";PACKET_TYPES["message"]="4";PACKET_TYPES["upgrade"]="5";PACKET_TYPES["noop"]="6";const PACKET_TYPES_REVERSE=Object.create(null);exports.PACKET_TYPES_REVERSE=PACKET_TYPES_REVERSE;Object.keys(PACKET_TYPES).forEach((key=>{PACKET_TYPES_REVERSE[PACKET_TYPES[key]]=key}));const ERROR_PACKET={type:"error",data:"parser error"};exports.ERROR_PACKET=ERROR_PACKET},{}],75:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const commons_js_1=require("./commons.js");const base64_arraybuffer_1=require("base64-arraybuffer");const withNativeArrayBuffer=typeof ArrayBuffer==="function";const decodePacket=(encodedPacket,binaryType)=>{if(typeof encodedPacket!=="string"){return{type:"message",data:mapBinary(encodedPacket,binaryType)}}const type=encodedPacket.charAt(0);if(type==="b"){return{type:"message",data:decodeBase64Packet(encodedPacket.substring(1),binaryType)}}const packetType=commons_js_1.PACKET_TYPES_REVERSE[type];if(!packetType){return commons_js_1.ERROR_PACKET}return encodedPacket.length>1?{type:commons_js_1.PACKET_TYPES_REVERSE[type],data:encodedPacket.substring(1)}:{type:commons_js_1.PACKET_TYPES_REVERSE[type]}};const decodeBase64Packet=(data,binaryType)=>{if(withNativeArrayBuffer){const decoded=(0,base64_arraybuffer_1.decode)(data);return mapBinary(decoded,binaryType)}else{return{base64:true,data:data}}};const mapBinary=(data,binaryType)=>{switch(binaryType){case"blob":return data instanceof ArrayBuffer?new Blob([data]):data;case"arraybuffer":default:return data}};exports.default=decodePacket},{"./commons.js":74,"base64-arraybuffer":28}],76:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});const commons_js_1=require("./commons.js");const withNativeBlob=typeof Blob==="function"||typeof Blob!=="undefined"&&Object.prototype.toString.call(Blob)==="[object BlobConstructor]";const withNativeArrayBuffer=typeof ArrayBuffer==="function";const isView=obj=>typeof ArrayBuffer.isView==="function"?ArrayBuffer.isView(obj):obj&&obj.buffer instanceof ArrayBuffer;const encodePacket=({type:type,data:data},supportsBinary,callback)=>{if(withNativeBlob&&data instanceof Blob){if(supportsBinary){return callback(data)}else{return encodeBlobAsBase64(data,callback)}}else if(withNativeArrayBuffer&&(data instanceof ArrayBuffer||isView(data))){if(supportsBinary){return callback(data)}else{return encodeBlobAsBase64(new Blob([data]),callback)}}return callback(commons_js_1.PACKET_TYPES[type]+(data||""))};const encodeBlobAsBase64=(data,callback)=>{const fileReader=new FileReader;fileReader.onload=function(){const content=fileReader.result.split(",")[1];callback("b"+content)};return fileReader.readAsDataURL(data)};exports.default=encodePacket},{"./commons.js":74}],77:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.decodePayload=exports.decodePacket=exports.encodePayload=exports.encodePacket=exports.protocol=void 0;const encodePacket_js_1=require("./encodePacket.js");exports.encodePacket=encodePacket_js_1.default;const decodePacket_js_1=require("./decodePacket.js");exports.decodePacket=decodePacket_js_1.default;const SEPARATOR=String.fromCharCode(30);const encodePayload=(packets,callback)=>{const length=packets.length;const encodedPackets=new Array(length);let count=0;packets.forEach(((packet,i)=>{(0,encodePacket_js_1.default)(packet,false,(encodedPacket=>{encodedPackets[i]=encodedPacket;if(++count===length){callback(encodedPackets.join(SEPARATOR))}}))}))};exports.encodePayload=encodePayload;const decodePayload=(encodedPayload,binaryType)=>{const encodedPackets=encodedPayload.split(SEPARATOR);const packets=[];for(let i=0;ioptions.depthLimit){setReplace(LIMIT_REPLACE_NODE,val,k,parent);return}if(typeof options.edgesLimit!=="undefined"&&edgeIndex+1>options.edgesLimit){setReplace(LIMIT_REPLACE_NODE,val,k,parent);return}stack.push(val);if(Array.isArray(val)){for(i=0;ib){return 1}return 0}function deterministicStringify(obj,replacer,spacer,options){if(typeof options==="undefined"){options=defaultOptions()}var tmp=deterministicDecirc(obj,"",0,[],undefined,0,options)||obj;var res;try{if(replacerStack.length===0){res=JSON.stringify(tmp,replacer,spacer)}else{res=JSON.stringify(tmp,replaceGetterValues(replacer),spacer)}}catch(_){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{while(arr.length!==0){var part=arr.pop();if(part.length===4){Object.defineProperty(part[0],part[1],part[3])}else{part[0][part[1]]=part[2]}}}return res}function deterministicDecirc(val,k,edgeIndex,stack,parent,depth,options){depth+=1;var i;if(typeof val==="object"&&val!==null){for(i=0;ioptions.depthLimit){setReplace(LIMIT_REPLACE_NODE,val,k,parent);return}if(typeof options.edgesLimit!=="undefined"&&edgeIndex+1>options.edgesLimit){setReplace(LIMIT_REPLACE_NODE,val,k,parent);return}stack.push(val);if(Array.isArray(val)){for(i=0;i0){for(var i=0;i1&&typeof allowMissing!=="boolean"){throw new $TypeError('"allowMissing" argument must be a boolean')}var parts=stringToPath(name);var intrinsicBaseName=parts.length>0?parts[0]:"";var intrinsic=getBaseIntrinsic("%"+intrinsicBaseName+"%",allowMissing);var intrinsicRealName=intrinsic.name;var value=intrinsic.value;var skipFurtherCaching=false;var alias=intrinsic.alias;if(alias){intrinsicBaseName=alias[0];$spliceApply(parts,$concat([0,1],alias))}for(var i=1,isOwn=true;i=parts.length){var desc=$gOPD(value,part);isOwn=!!desc;if(isOwn&&"get"in desc&&!("originalValue"in desc.get)){value=desc.get}else{value=value[part]}}else{isOwn=hasOwn(value,part);value=value[part]}if(isOwn&&!skipFurtherCaching){INTRINSICS[intrinsicRealName]=value}}}return value}},{"function-bind":81,has:89,"has-symbols":87}],84:[function(require,module,exports){(function(global){(function(){var topLevel=typeof global!=="undefined"?global:typeof window!=="undefined"?window:{};var minDoc=require("min-document");var doccy;if(typeof document!=="undefined"){doccy=document}else{doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"];if(!doccy){doccy=topLevel["__GLOBAL_DOCUMENT_CACHE@4"]=minDoc}}module.exports=doccy}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"min-document":30}],85:[function(require,module,exports){(function(global){(function(){var win;if(typeof window!=="undefined"){win=window}else if(typeof global!=="undefined"){win=global}else if(typeof self!=="undefined"){win=self}else{win={}}module.exports=win}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],86:[function(require,module,exports){try{module.exports=typeof XMLHttpRequest!=="undefined"&&"withCredentials"in new XMLHttpRequest}catch(err){module.exports=false}},{}],87:[function(require,module,exports){"use strict";var origSymbol=typeof Symbol!=="undefined"&&Symbol;var hasSymbolSham=require("./shams");module.exports=function hasNativeSymbols(){if(typeof origSymbol!=="function"){return false}if(typeof Symbol!=="function"){return false}if(typeof origSymbol("foo")!=="symbol"){return false}if(typeof Symbol("bar")!=="symbol"){return false}return hasSymbolSham()}},{"./shams":88}],88:[function(require,module,exports){"use strict";module.exports=function hasSymbols(){if(typeof Symbol!=="function"||typeof Object.getOwnPropertySymbols!=="function"){return false}if(typeof Symbol.iterator==="symbol"){return true}var obj={};var sym=Symbol("test");var symObj=Object(sym);if(typeof sym==="string"){return false}if(Object.prototype.toString.call(sym)!=="[object Symbol]"){return false}if(Object.prototype.toString.call(symObj)!=="[object Symbol]"){return false}var symVal=42;obj[sym]=symVal;for(sym in obj){return false}if(typeof Object.keys==="function"&&Object.keys(obj).length!==0){return false}if(typeof Object.getOwnPropertyNames==="function"&&Object.getOwnPropertyNames(obj).length!==0){return false}var syms=Object.getOwnPropertySymbols(obj);if(syms.length!==1||syms[0]!==sym){return false}if(!Object.prototype.propertyIsEnumerable.call(obj,sym)){return false}if(typeof Object.getOwnPropertyDescriptor==="function"){var descriptor=Object.getOwnPropertyDescriptor(obj,sym);if(descriptor.value!==symVal||descriptor.enumerable!==true){return false}}return true}},{}],89:[function(require,module,exports){"use strict";var bind=require("function-bind");module.exports=bind.call(Function.call,Object.prototype.hasOwnProperty)},{"function-bind":81}],90:[function(require,module,exports){const Output=require("./src/output.js");const loop=require("raf-loop");const Source=require("./src/hydra-source.js");const Mouse=require("./src/lib/mouse.js")();const Audio=require("./src/lib/audio.js");const VidRecorder=require("./src/lib/video-recorder.js");const ArrayUtils=require("./src/lib/array-utils.js");const Sandbox=require("./src/eval-sandbox.js");const Generator=require("./src/generator-factory.js");class HydraRenderer{constructor({pb:pb=null,width:width=1280,height:height=720,numSources:numSources=4,numOutputs:numOutputs=4,makeGlobal:makeGlobal=true,autoLoop:autoLoop=true,detectAudio:detectAudio=true,enableStreamCapture:enableStreamCapture=true,canvas:canvas,precision:precision,extendTransforms:extendTransforms={}}={}){ArrayUtils.init();this.pb=pb;this.width=width;this.height=height;this.renderAll=false;this.detectAudio=detectAudio;this._initCanvas(canvas);this.synth={time:0,bpm:30,width:this.width,height:this.height,fps:undefined,stats:{fps:0},speed:1,mouse:Mouse,render:this._render.bind(this),setResolution:this.setResolution.bind(this),update:dt=>{},hush:this.hush.bind(this)};if(makeGlobal)window.loadScript=this.loadScript;this.timeSinceLastUpdate=0;this._time=0;let precisionOptions=["lowp","mediump","highp"];if(precision&&precisionOptions.includes(precision.toLowerCase())){this.precision=precision.toLowerCase()}else{let isIOS=(/iPad|iPhone|iPod/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)&&!window.MSStream;this.precision=isIOS?"highp":"mediump"}this.extendTransforms=extendTransforms;this.saveFrame=false;this.captureStream=null;this.generator=undefined;this._initRegl();this._initOutputs(numOutputs);this._initSources(numSources);this._generateGlslTransforms();this.synth.screencap=()=>{this.saveFrame=true};if(enableStreamCapture){try{this.captureStream=this.canvas.captureStream(25);this.synth.vidRecorder=new VidRecorder(this.captureStream)}catch(e){console.warn("[hydra-synth warning]\nnew MediaSource() is not currently supported on iOS.");console.error(e)}}if(detectAudio)this._initAudio();if(autoLoop)loop(this.tick.bind(this)).start();this.sandbox=new Sandbox(this.synth,makeGlobal,["speed","update","bpm","fps"])}eval(code){this.sandbox.eval(code)}getScreenImage(callback){this.imageCallback=callback;this.saveFrame=true}hush(){this.s.forEach((source=>{source.clear()}));this.o.forEach((output=>{this.synth.solid(0,0,0,0).out(output)}));this.synth.render(this.o[0])}loadScript(url=""){const p=new Promise(((res,rej)=>{var script=document.createElement("script");script.onload=function(){console.log(`loaded script ${url}`);res()};script.onerror=err=>{console.log(`error loading script ${url}`,"log-error");res()};script.src=url;document.head.appendChild(script)}));return p}setResolution(width,height){this.canvas.width=width;this.canvas.height=height;this.width=width;this.height=height;this.sandbox.set("width",width);this.sandbox.set("height",height);console.log(this.width);this.o.forEach((output=>{output.resize(width,height)}));this.s.forEach((source=>{source.resize(width,height)}));this.regl._refresh();console.log(this.canvas.width)}canvasToImage(callback){const a=document.createElement("a");a.style.display="none";let d=new Date;a.download=`hydra-${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.png`;document.body.appendChild(a);var self=this;this.canvas.toBlob((blob=>{if(self.imageCallback){self.imageCallback(blob);delete self.imageCallback}else{a.href=URL.createObjectURL(blob);console.log(a.href);a.click()}}),"image/png");setTimeout((()=>{document.body.removeChild(a);window.URL.revokeObjectURL(a.href)}),300)}_initAudio(){const that=this;this.synth.a=new Audio({numBins:4})}_initCanvas(canvas){if(canvas){this.canvas=canvas;this.width=canvas.width;this.height=canvas.height}else{this.canvas=document.createElement("canvas");this.canvas.width=this.width;this.canvas.height=this.height;this.canvas.style.width="100%";this.canvas.style.height="100%";this.canvas.style.imageRendering="pixelated";document.body.appendChild(this.canvas)}}_initRegl(){this.regl=require("regl")({canvas:this.canvas,pixelRatio:1});this.regl.clear({color:[0,0,0,1]});this.renderAll=this.regl({frag:`\n precision ${this.precision} float;\n varying vec2 uv;\n uniform sampler2D tex0;\n uniform sampler2D tex1;\n uniform sampler2D tex2;\n uniform sampler2D tex3;\n\n void main () {\n vec2 st = vec2(1.0 - uv.x, uv.y);\n st*= vec2(2);\n vec2 q = floor(st).xy*(vec2(2.0, 1.0));\n int quad = int(q.x) + int(q.y);\n st.x += step(1., mod(st.y,2.0));\n st.y += step(1., mod(st.x,2.0));\n st = fract(st);\n if(quad==0){\n gl_FragColor = texture2D(tex0, st);\n } else if(quad==1){\n gl_FragColor = texture2D(tex1, st);\n } else if (quad==2){\n gl_FragColor = texture2D(tex2, st);\n } else {\n gl_FragColor = texture2D(tex3, st);\n }\n\n }\n `,vert:`\n precision ${this.precision} float;\n attribute vec2 position;\n varying vec2 uv;\n\n void main () {\n uv = position;\n gl_Position = vec4(1.0 - 2.0 * position, 0, 1);\n }`,attributes:{position:[[-2,0],[0,-2],[2,2]]},uniforms:{tex0:this.regl.prop("tex0"),tex1:this.regl.prop("tex1"),tex2:this.regl.prop("tex2"),tex3:this.regl.prop("tex3")},count:3,depth:{enable:false}});this.renderFbo=this.regl({frag:`\n precision ${this.precision} float;\n varying vec2 uv;\n uniform vec2 resolution;\n uniform sampler2D tex0;\n\n void main () {\n gl_FragColor = texture2D(tex0, vec2(1.0 - uv.x, uv.y));\n }\n `,vert:`\n precision ${this.precision} float;\n attribute vec2 position;\n varying vec2 uv;\n\n void main () {\n uv = position;\n gl_Position = vec4(1.0 - 2.0 * position, 0, 1);\n }`,attributes:{position:[[-2,0],[0,-2],[2,2]]},uniforms:{tex0:this.regl.prop("tex0"),resolution:this.regl.prop("resolution")},count:3,depth:{enable:false}})}_initOutputs(numOutputs){const self=this;this.o=Array(numOutputs).fill().map(((el,index)=>{var o=new Output({regl:this.regl,width:this.width,height:this.height,precision:this.precision,label:`o${index}`});o.id=index;self.synth["o"+index]=o;return o}));this.output=this.o[0]}_initSources(numSources){this.s=[];for(var i=0;i{if(type==="add"){self.synth[method]=synth.generators[method];if(self.sandbox)self.sandbox.add(method)}else if(type==="remove"){}}});this.synth.setFunction=this.generator.setFunction.bind(this.generator)}_render(output){if(output){this.output=output;this.isRenderingAll=false}else{this.isRenderingAll=true}}tick(dt,uniforms){this.sandbox.tick();if(this.detectAudio===true)this.synth.a.tick();if(this.synth.update){try{this.synth.update(dt)}catch(e){console.log(error)}}this.sandbox.set("time",this.synth.time+=dt*.001*this.synth.speed);this.timeSinceLastUpdate+=dt;if(!this.synth.fps||this.timeSinceLastUpdate>=1e3/this.synth.fps){this.synth.stats.fps=Math.ceil(1e3/this.timeSinceLastUpdate);for(let i=0;ithis.add(property)));this.userProps=userProps}add(name){if(this.makeGlobal)window[name]=this.parent[name];this.sandbox.addToContext(name,`parent.${name}`)}set(property,value){if(this.makeGlobal){window[property]=value}this.parent[property]=value}tick(){if(this.makeGlobal){this.userProps.forEach((property=>{this.parent[property]=window[property]}))}else{}}eval(code){this.sandbox.eval(code)}}module.exports=EvalSandbox},{"./lib/array-utils.js":100,"./lib/sandbox.js":105}],93:[function(require,module,exports){const arrayUtils=require("./lib/array-utils.js");const DEFAULT_CONVERSIONS={float:{vec4:{name:"sum",args:[[1,1,1,1]]},vec2:{name:"sum",args:[[1,1]]}}};function fillArrayWithDefaults(arr,len){while(arr.length{val=val.toString();if(val.indexOf(".")<0){val+="."}return val};module.exports=function formatArguments(transform,startIndex,synthContext){const defaultArgs=transform.transform.inputs;const userArgs=transform.userArgs;const{generators:generators}=transform.synth;const{src:src}=generators;return defaultArgs.map(((input,index)=>{const typedArg={value:input.default,type:input.type,isUniform:false,name:input.name,vecLen:0};if(typedArg.type==="float")typedArg.value=ensure_decimal_dot(input.default);if(input.type.startsWith("vec")){try{typedArg.vecLen=Number.parseInt(input.type.substr(3))}catch(e){console.log(`Error determining length of vector input type ${input.type} (${input.name})`)}}if(userArgs.length>index){typedArg.value=userArgs[index];if(typeof userArgs[index]==="function"){typedArg.value=(context,props,batchId)=>{try{return userArgs[index](props)}catch(e){console.log("ERROR",e);return input.default}};typedArg.isUniform=true}else if(userArgs[index].constructor===Array){typedArg.value=(context,props,batchId)=>arrayUtils.getValue(userArgs[index])(props);typedArg.isUniform=true}}if(startIndex<0){}else{if(typedArg.value&&typedArg.value.transforms){const final_transform=typedArg.value.transforms[typedArg.value.transforms.length-1];if(final_transform.transform.glsl_return_type!==input.type){const defaults=DEFAULT_CONVERSIONS[input.type];if(typeof defaults!=="undefined"){const default_def=defaults[final_transform.transform.glsl_return_type];if(typeof default_def!=="undefined"){const{name:name,args:args}=default_def;typedArg.value=typedArg.value[name](...args)}}}typedArg.isUniform=false}else if(typedArg.type==="float"&&typeof typedArg.value==="number"){typedArg.value=ensure_decimal_dot(typedArg.value)}else if(typedArg.type.startsWith("vec")&&typeof typedArg.value==="object"&&Array.isArray(typedArg.value)){typedArg.isUniform=false;typedArg.value=`${typedArg.type}(${typedArg.value.map(ensure_decimal_dot).join(", ")})`}else if(input.type==="sampler2D"){var x=typedArg.value;typedArg.value=()=>x.getTexture();typedArg.isUniform=true}else{if(typedArg.value.getTexture&&input.type==="vec4"){var x1=typedArg.value;typedArg.value=src(x1);typedArg.isUniform=false}}if(typedArg.isUniform){typedArg.name+=startIndex}}return typedArg}))}},{"./lib/array-utils.js":100}],94:[function(require,module,exports){const formatArguments=require("./format-arguments.js");const arrayUtils=require("./lib/array-utils.js");module.exports=function(transforms){var shaderParams={uniforms:[],glslFunctions:[],fragColor:""};var gen=generateGlsl(transforms,shaderParams)("st");shaderParams.fragColor=gen;let uniforms={};shaderParams.uniforms.forEach((uniform=>uniforms[uniform.name]=uniform));shaderParams.uniforms=Object.values(uniforms);return shaderParams};function generateGlsl(transforms,shaderParams){var fragColor=()=>"";transforms.forEach((transform=>{var inputs=formatArguments(transform,shaderParams.uniforms.length);inputs.forEach((input=>{if(input.isUniform)shaderParams.uniforms.push(input)}));if(!contains(transform,shaderParams.glslFunctions))shaderParams.glslFunctions.push(transform);var f0=fragColor;if(transform.transform.type==="src"){fragColor=uv=>`${shaderString(uv,transform.name,inputs,shaderParams)}`}else if(transform.transform.type==="coord"){fragColor=uv=>`${f0(`${shaderString(uv,transform.name,inputs,shaderParams)}`)}`}else if(transform.transform.type==="color"){fragColor=uv=>`${shaderString(`${f0(uv)}`,transform.name,inputs,shaderParams)}`}else if(transform.transform.type==="combine"){var f1=inputs[0].value&&inputs[0].value.transforms?uv=>`${generateGlsl(inputs[0].value.transforms,shaderParams)(uv)}`:inputs[0].isUniform?()=>inputs[0].name:()=>inputs[0].value;fragColor=uv=>`${shaderString(`${f0(uv)}, ${f1(uv)}`,transform.name,inputs.slice(1),shaderParams)}`}else if(transform.transform.type==="combineCoord"){var f1=inputs[0].value&&inputs[0].value.transforms?uv=>`${generateGlsl(inputs[0].value.transforms,shaderParams)(uv)}`:inputs[0].isUniform?()=>inputs[0].name:()=>inputs[0].value;fragColor=uv=>`${f0(`${shaderString(`${uv}, ${f1(uv)}`,transform.name,inputs.slice(1),shaderParams)}`)}`}}));return fragColor}function shaderString(uv,method,inputs,shaderParams){const str=inputs.map((input=>{if(input.isUniform){return input.name}else if(input.value&&input.value.transforms){return`${generateGlsl(input.value.transforms,shaderParams)("st")}`}return input.value})).reduce(((p,c)=>`${p}, ${c}`),"");return`${method}(${uv}${str})`}function mergeArrays(a,b){return a.concat(b.filter((function(item){return a.indexOf(item)<0})))}function contains(object,arr){for(var i=0;i{})}={}){this.defaultOutput=defaultOutput;this.defaultUniforms=defaultUniforms;this.changeListener=changeListener;this.extendTransforms=extendTransforms;this.generators={};this.init()}init(){this.glslTransforms={};this.generators=Object.entries(this.generators).reduce(((prev,[method,transform])=>{this.changeListener({type:"remove",synth:this,method:method});return prev}),{});this.sourceClass=(()=>class extends GlslSource{})();let functions=require("./glsl/glsl-functions.js")();if(Array.isArray(this.extendTransforms)){functions.concat(this.extendTransforms)}else if(typeof this.extendTransforms==="object"&&this.extendTransforms.type){functions.push(this.extendTransforms)}return functions.map((transform=>this.setFunction(transform)))}_addMethod(method,transform){const self=this;this.glslTransforms[method]=transform;if(transform.type==="src"){const func=(...args)=>new this.sourceClass({name:method,transform:transform,userArgs:args,defaultOutput:this.defaultOutput,defaultUniforms:this.defaultUniforms,synth:self});this.generators[method]=func;this.changeListener({type:"add",synth:this,method:method});return func}else{this.sourceClass.prototype[method]=function(...args){this.transforms.push({name:method,transform:transform,userArgs:args,synth:self});return this}}return undefined}setFunction(obj){var processedGlsl=processGlsl(obj);if(processedGlsl)this._addMethod(obj.name,processedGlsl)}}const typeLookup={src:{returnType:"vec4",args:["vec2 _st"]},coord:{returnType:"vec2",args:["vec2 _st"]},color:{returnType:"vec4",args:["vec4 _c0"]},combine:{returnType:"vec4",args:["vec4 _c0","vec4 _c1"]},combineCoord:{returnType:"vec2",args:["vec2 _st","vec4 _c0"]}};function processGlsl(obj){let t=typeLookup[obj.type];if(t){let baseArgs=t.args.map((arg=>arg)).join(", ");let customArgs=obj.inputs.map((input=>`${input.type} ${input.name}`)).join(", ");let args=`${baseArgs}${customArgs.length>0?", "+customArgs:""}`;let glslFunction=`\n ${t.returnType} ${obj.name}(${args}) {\n ${obj.glsl}\n }\n`;if(obj.type==="combine"||obj.type==="combineCoord")obj.inputs.unshift({name:"color",type:"vec4"});return Object.assign({},obj,{glsl:glslFunction})}else{console.warn(`type ${obj.type} not recognized`,obj)}}module.exports=GeneratorFactory},{"./glsl-source.js":96,"./glsl/glsl-functions.js":97}],96:[function(require,module,exports){const generateGlsl=require("./generate-glsl.js");const utilityGlsl=require("./glsl/utility-functions.js");var GlslSource=function(obj){this.transforms=[];this.transforms.push(obj);this.defaultOutput=obj.defaultOutput;this.synth=obj.synth;this.type="GlslSource";this.defaultUniforms=obj.defaultUniforms;return this};GlslSource.prototype.addTransform=function(obj){this.transforms.push(obj)};GlslSource.prototype.out=function(_output){var output=_output||this.defaultOutput;var glsl=this.glsl(output);this.synth.currentFunctions=[];if(output)try{output.render(glsl)}catch(error){console.log("shader could not compile",error)}};GlslSource.prototype.glsl=function(){var self=this;var passes=[];var transforms=[];this.transforms.forEach((transform=>{if(transform.transform.type==="renderpass"){console.warn("no support for renderpass")}else{transforms.push(transform)}}));if(transforms.length>0)passes.push(this.compile(transforms));return passes};GlslSource.prototype.compile=function(transforms){var shaderInfo=generateGlsl(transforms,this.synth);var uniforms={};shaderInfo.uniforms.forEach((uniform=>{uniforms[uniform.name]=uniform.value}));var frag=`\n precision ${this.defaultOutput.precision} float;\n ${Object.values(shaderInfo.uniforms).map((uniform=>{let type=uniform.type;switch(uniform.type){case"texture":type="sampler2D";break}return`\n uniform ${type} ${uniform.name};`})).join("")}\n uniform float time;\n uniform vec2 resolution;\n varying vec2 uv;\n uniform sampler2D prevBuffer;\n\n ${Object.values(utilityGlsl).map((transform=>`\n ${transform.glsl}\n `)).join("")}\n\n ${shaderInfo.glslFunctions.map((transform=>`\n ${transform.transform.glsl}\n `)).join("")}\n\n void main () {\n vec4 c = vec4(1, 0, 0, 1);\n vec2 st = gl_FragCoord.xy/resolution.xy;\n gl_FragColor = ${shaderInfo.fragColor};\n }\n `;return{frag:frag,uniforms:Object.assign({},this.defaultUniforms,uniforms)}};module.exports=GlslSource},{"./generate-glsl.js":94,"./glsl/utility-functions.js":98}],97:[function(require,module,exports){module.exports=()=>[{name:"noise",type:"src",inputs:[{type:"float",name:"scale",default:10},{type:"float",name:"offset",default:.1}],glsl:` return vec4(vec3(_noise(vec3(_st*scale, offset*time))), 1.0);`},{name:"voronoi",type:"src",inputs:[{type:"float",name:"scale",default:5},{type:"float",name:"speed",default:.3},{type:"float",name:"blending",default:.3}],glsl:` vec3 color = vec3(.0);\n // Scale\n _st *= scale;\n // Tile the space\n vec2 i_st = floor(_st);\n vec2 f_st = fract(_st);\n float m_dist = 10.; // minimun distance\n vec2 m_point; // minimum point\n for (int j=-1; j<=1; j++ ) {\n for (int i=-1; i<=1; i++ ) {\n vec2 neighbor = vec2(float(i),float(j));\n vec2 p = i_st + neighbor;\n vec2 point = fract(sin(vec2(dot(p,vec2(127.1,311.7)),dot(p,vec2(269.5,183.3))))*43758.5453);\n point = 0.5 + 0.5*sin(time*speed + 6.2831*point);\n vec2 diff = neighbor + point - f_st;\n float dist = length(diff);\n if( dist < m_dist ) {\n m_dist = dist;\n m_point = point;\n }\n }\n }\n // Assign a color using the closest point position\n color += dot(m_point,vec2(.3,.6));\n color *= 1.0 - blending*m_dist;\n return vec4(color, 1.0);`},{name:"osc",type:"src",inputs:[{type:"float",name:"frequency",default:60},{type:"float",name:"sync",default:.1},{type:"float",name:"offset",default:0}],glsl:` vec2 st = _st;\n float r = sin((st.x-offset/frequency+time*sync)*frequency)*0.5 + 0.5;\n float g = sin((st.x+time*sync)*frequency)*0.5 + 0.5;\n float b = sin((st.x+offset/frequency+time*sync)*frequency)*0.5 + 0.5;\n return vec4(r, g, b, 1.0);`},{name:"shape",type:"src",inputs:[{type:"float",name:"sides",default:3},{type:"float",name:"radius",default:.3},{type:"float",name:"smoothing",default:.01}],glsl:` vec2 st = _st * 2. - 1.;\n // Angle and radius from the current pixel\n float a = atan(st.x,st.y)+3.1416;\n float r = (2.*3.1416)/sides;\n float d = cos(floor(.5+a/r)*r-a)*length(st);\n return vec4(vec3(1.0-smoothstep(radius,radius + smoothing + 0.0000001,d)), 1.0);`},{name:"gradient",type:"src",inputs:[{type:"float",name:"speed",default:0}],glsl:` return vec4(_st, sin(time*speed), 1.0);`},{name:"src",type:"src",inputs:[{type:"sampler2D",name:"tex",default:NaN}],glsl:` // vec2 uv = gl_FragCoord.xy/vec2(1280., 720.);\n return texture2D(tex, fract(_st));`},{name:"solid",type:"src",inputs:[{type:"float",name:"r",default:0},{type:"float",name:"g",default:0},{type:"float",name:"b",default:0},{type:"float",name:"a",default:1}],glsl:` return vec4(r, g, b, a);`},{name:"rotate",type:"coord",inputs:[{type:"float",name:"angle",default:10},{type:"float",name:"speed",default:0}],glsl:` vec2 xy = _st - vec2(0.5);\n float ang = angle + speed *time;\n xy = mat2(cos(ang),-sin(ang), sin(ang),cos(ang))*xy;\n xy += 0.5;\n return xy;`},{name:"scale",type:"coord",inputs:[{type:"float",name:"amount",default:1.5},{type:"float",name:"xMult",default:1},{type:"float",name:"yMult",default:1},{type:"float",name:"offsetX",default:.5},{type:"float",name:"offsetY",default:.5}],glsl:` vec2 xy = _st - vec2(offsetX, offsetY);\n xy*=(1.0/vec2(amount*xMult, amount*yMult));\n xy+=vec2(offsetX, offsetY);\n return xy;\n `},{name:"pixelate",type:"coord",inputs:[{type:"float",name:"pixelX",default:20},{type:"float",name:"pixelY",default:20}],glsl:` vec2 xy = vec2(pixelX, pixelY);\n return (floor(_st * xy) + 0.5)/xy;`},{name:"posterize",type:"color",inputs:[{type:"float",name:"bins",default:3},{type:"float",name:"gamma",default:.6}],glsl:` vec4 c2 = pow(_c0, vec4(gamma));\n c2 *= vec4(bins);\n c2 = floor(c2);\n c2/= vec4(bins);\n c2 = pow(c2, vec4(1.0/gamma));\n return vec4(c2.xyz, _c0.a);`},{name:"shift",type:"color",inputs:[{type:"float",name:"r",default:.5},{type:"float",name:"g",default:0},{type:"float",name:"b",default:0},{type:"float",name:"a",default:0}],glsl:` vec4 c2 = vec4(_c0);\n c2.r = fract(c2.r + r);\n c2.g = fract(c2.g + g);\n c2.b = fract(c2.b + b);\n c2.a = fract(c2.a + a);\n return vec4(c2.rgba);`},{name:"repeat",type:"coord",inputs:[{type:"float",name:"repeatX",default:3},{type:"float",name:"repeatY",default:3},{type:"float",name:"offsetX",default:0},{type:"float",name:"offsetY",default:0}],glsl:` vec2 st = _st * vec2(repeatX, repeatY);\n st.x += step(1., mod(st.y,2.0)) * offsetX;\n st.y += step(1., mod(st.x,2.0)) * offsetY;\n return fract(st);`},{name:"modulateRepeat",type:"combineCoord",inputs:[{type:"float",name:"repeatX",default:3},{type:"float",name:"repeatY",default:3},{type:"float",name:"offsetX",default:.5},{type:"float",name:"offsetY",default:.5}],glsl:` vec2 st = _st * vec2(repeatX, repeatY);\n st.x += step(1., mod(st.y,2.0)) + _c0.r * offsetX;\n st.y += step(1., mod(st.x,2.0)) + _c0.g * offsetY;\n return fract(st);`},{name:"repeatX",type:"coord",inputs:[{type:"float",name:"reps",default:3},{type:"float",name:"offset",default:0}],glsl:` vec2 st = _st * vec2(reps, 1.0);\n // float f = mod(_st.y,2.0);\n st.y += step(1., mod(st.x,2.0))* offset;\n return fract(st);`},{name:"modulateRepeatX",type:"combineCoord",inputs:[{type:"float",name:"reps",default:3},{type:"float",name:"offset",default:.5}],glsl:` vec2 st = _st * vec2(reps, 1.0);\n // float f = mod(_st.y,2.0);\n st.y += step(1., mod(st.x,2.0)) + _c0.r * offset;\n return fract(st);`},{name:"repeatY",type:"coord",inputs:[{type:"float",name:"reps",default:3},{type:"float",name:"offset",default:0}],glsl:` vec2 st = _st * vec2(1.0, reps);\n // float f = mod(_st.y,2.0);\n st.x += step(1., mod(st.y,2.0))* offset;\n return fract(st);`},{name:"modulateRepeatY",type:"combineCoord",inputs:[{type:"float",name:"reps",default:3},{type:"float",name:"offset",default:.5}],glsl:` vec2 st = _st * vec2(reps, 1.0);\n // float f = mod(_st.y,2.0);\n st.x += step(1., mod(st.y,2.0)) + _c0.r * offset;\n return fract(st);`},{name:"kaleid",type:"coord",inputs:[{type:"float",name:"nSides",default:4}],glsl:` vec2 st = _st;\n st -= 0.5;\n float r = length(st);\n float a = atan(st.y, st.x);\n float pi = 2.*3.1416;\n a = mod(a,pi/nSides);\n a = abs(a-pi/nSides/2.);\n return r*vec2(cos(a), sin(a));`},{name:"modulateKaleid",type:"combineCoord",inputs:[{type:"float",name:"nSides",default:4}],glsl:` vec2 st = _st - 0.5;\n float r = length(st);\n float a = atan(st.y, st.x);\n float pi = 2.*3.1416;\n a = mod(a,pi/nSides);\n a = abs(a-pi/nSides/2.);\n return (_c0.r+r)*vec2(cos(a), sin(a));`},{name:"scroll",type:"coord",inputs:[{type:"float",name:"scrollX",default:.5},{type:"float",name:"scrollY",default:.5},{type:"float",name:"speedX",default:0},{type:"float",name:"speedY",default:0}],glsl:`\n _st.x += scrollX + time*speedX;\n _st.y += scrollY + time*speedY;\n return fract(_st);`},{name:"scrollX",type:"coord",inputs:[{type:"float",name:"scrollX",default:.5},{type:"float",name:"speed",default:0}],glsl:` _st.x += scrollX + time*speed;\n return fract(_st);`},{name:"modulateScrollX",type:"combineCoord",inputs:[{type:"float",name:"scrollX",default:.5},{type:"float",name:"speed",default:0}],glsl:` _st.x += _c0.r*scrollX + time*speed;\n return fract(_st);`},{name:"scrollY",type:"coord",inputs:[{type:"float",name:"scrollY",default:.5},{type:"float",name:"speed",default:0}],glsl:` _st.y += scrollY + time*speed;\n return fract(_st);`},{name:"modulateScrollY",type:"combineCoord",inputs:[{type:"float",name:"scrollY",default:.5},{type:"float",name:"speed",default:0}],glsl:` _st.y += _c0.r*scrollY + time*speed;\n return fract(_st);`},{name:"add",type:"combine",inputs:[{type:"float",name:"amount",default:1}],glsl:` return (_c0+_c1)*amount + _c0*(1.0-amount);`},{name:"sub",type:"combine",inputs:[{type:"float",name:"amount",default:1}],glsl:` return (_c0-_c1)*amount + _c0*(1.0-amount);`},{name:"layer",type:"combine",inputs:[],glsl:` return vec4(mix(_c0.rgb, _c1.rgb, _c1.a), clamp(_c0.a + _c1.a, 0.0, 1.0));`},{name:"blend",type:"combine",inputs:[{type:"float",name:"amount",default:.5}],glsl:` return _c0*(1.0-amount)+_c1*amount;`},{name:"mult",type:"combine",inputs:[{type:"float",name:"amount",default:1}],glsl:` return _c0*(1.0-amount)+(_c0*_c1)*amount;`},{name:"diff",type:"combine",inputs:[],glsl:` return vec4(abs(_c0.rgb-_c1.rgb), max(_c0.a, _c1.a));`},{name:"modulate",type:"combineCoord",inputs:[{type:"float",name:"amount",default:.1}],glsl:` // return fract(st+(_c0.xy-0.5)*amount);\n return _st + _c0.xy*amount;`},{name:"modulateScale",type:"combineCoord",inputs:[{type:"float",name:"multiple",default:1},{type:"float",name:"offset",default:1}],glsl:` vec2 xy = _st - vec2(0.5);\n xy*=(1.0/vec2(offset + multiple*_c0.r, offset + multiple*_c0.g));\n xy+=vec2(0.5);\n return xy;`},{name:"modulatePixelate",type:"combineCoord",inputs:[{type:"float",name:"multiple",default:10},{type:"float",name:"offset",default:3}],glsl:` vec2 xy = vec2(offset + _c0.x*multiple, offset + _c0.y*multiple);\n return (floor(_st * xy) + 0.5)/xy;`},{name:"modulateRotate",type:"combineCoord",inputs:[{type:"float",name:"multiple",default:1},{type:"float",name:"offset",default:0}],glsl:` vec2 xy = _st - vec2(0.5);\n float angle = offset + _c0.x * multiple;\n xy = mat2(cos(angle),-sin(angle), sin(angle),cos(angle))*xy;\n xy += 0.5;\n return xy;`},{name:"modulateHue",type:"combineCoord",inputs:[{type:"float",name:"amount",default:1}],glsl:` return _st + (vec2(_c0.g - _c0.r, _c0.b - _c0.g) * amount * 1.0/resolution);`},{name:"invert",type:"color",inputs:[{type:"float",name:"amount",default:1}],glsl:` return vec4((1.0-_c0.rgb)*amount + _c0.rgb*(1.0-amount), _c0.a);`},{name:"contrast",type:"color",inputs:[{type:"float",name:"amount",default:1.6}],glsl:` vec4 c = (_c0-vec4(0.5))*vec4(amount) + vec4(0.5);\n return vec4(c.rgb, _c0.a);`},{name:"brightness",type:"color",inputs:[{type:"float",name:"amount",default:.4}],glsl:` return vec4(_c0.rgb + vec3(amount), _c0.a);`},{name:"mask",type:"combine",inputs:[],glsl:` float a = _luminance(_c1.rgb);\n return vec4(_c0.rgb*a, a*_c0.a);`},{name:"luma",type:"color",inputs:[{type:"float",name:"threshold",default:.5},{type:"float",name:"tolerance",default:.1}],glsl:` float a = smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb));\n return vec4(_c0.rgb*a, a);`},{name:"thresh",type:"color",inputs:[{type:"float",name:"threshold",default:.5},{type:"float",name:"tolerance",default:.04}],glsl:` return vec4(vec3(smoothstep(threshold-(tolerance+0.0000001), threshold+(tolerance+0.0000001), _luminance(_c0.rgb))), _c0.a);`},{name:"color",type:"color",inputs:[{type:"float",name:"r",default:1},{type:"float",name:"g",default:1},{type:"float",name:"b",default:1},{type:"float",name:"a",default:1}],glsl:` vec4 c = vec4(r, g, b, a);\n vec4 pos = step(0.0, c); // detect whether negative\n // if > 0, return r * _c0\n // if < 0 return (1.0-r) * _c0\n return vec4(mix((1.0-_c0)*abs(c), c*_c0, pos));`},{name:"saturate",type:"color",inputs:[{type:"float",name:"amount",default:2}],glsl:` const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n vec3 intensity = vec3(dot(_c0.rgb, W));\n return vec4(mix(intensity, _c0.rgb, amount), _c0.a);`},{name:"hue",type:"color",inputs:[{type:"float",name:"hue",default:.4}],glsl:` vec3 c = _rgbToHsv(_c0.rgb);\n c.r += hue;\n // c.r = fract(c.r);\n return vec4(_hsvToRgb(c), _c0.a);`},{name:"colorama",type:"color",inputs:[{type:"float",name:"amount",default:.005}],glsl:` vec3 c = _rgbToHsv(_c0.rgb);\n c += vec3(amount);\n c = _hsvToRgb(c);\n c = fract(c);\n return vec4(c, _c0.a);`},{name:"prev",type:"src",inputs:[],glsl:` return texture2D(prevBuffer, fract(_st));`},{name:"sum",type:"color",inputs:[{type:"vec4",name:"scale",default:1}],glsl:` vec4 v = _c0 * s;\n return v.r + v.g + v.b + v.a;\n }\n float sum(vec2 _st, vec4 s) { // vec4 is not a typo, because argument type is not overloaded\n vec2 v = _st.xy * s.xy;\n return v.x + v.y;`},{name:"r",type:"color",inputs:[{type:"float",name:"scale",default:1},{type:"float",name:"offset",default:0}],glsl:` return vec4(_c0.r * scale + offset);`},{name:"g",type:"color",inputs:[{type:"float",name:"scale",default:1},{type:"float",name:"offset",default:0}],glsl:` return vec4(_c0.g * scale + offset);`},{name:"b",type:"color",inputs:[{type:"float",name:"scale",default:1},{type:"float",name:"offset",default:0}],glsl:` return vec4(_c0.b * scale + offset);`},{name:"a",type:"color",inputs:[{type:"float",name:"scale",default:1},{type:"float",name:"offset",default:0}],glsl:` return vec4(_c0.a * scale + offset);`}]},{}],98:[function(require,module,exports){module.exports={_luminance:{type:"util",glsl:`float _luminance(vec3 rgb){\n const vec3 W = vec3(0.2125, 0.7154, 0.0721);\n return dot(rgb, W);\n }`},_noise:{type:"util",glsl:`\n //\tSimplex 3D Noise\n //\tby Ian McEwan, Ashima Arts\n vec4 permute(vec4 x){return mod(((x*34.0)+1.0)*x, 289.0);}\n vec4 taylorInvSqrt(vec4 r){return 1.79284291400159 - 0.85373472095314 * r;}\n\n float _noise(vec3 v){\n const vec2 C = vec2(1.0/6.0, 1.0/3.0) ;\n const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);\n\n // First corner\n vec3 i = floor(v + dot(v, C.yyy) );\n vec3 x0 = v - i + dot(i, C.xxx) ;\n\n // Other corners\n vec3 g = step(x0.yzx, x0.xyz);\n vec3 l = 1.0 - g;\n vec3 i1 = min( g.xyz, l.zxy );\n vec3 i2 = max( g.xyz, l.zxy );\n\n // x0 = x0 - 0. + 0.0 * C\n vec3 x1 = x0 - i1 + 1.0 * C.xxx;\n vec3 x2 = x0 - i2 + 2.0 * C.xxx;\n vec3 x3 = x0 - 1. + 3.0 * C.xxx;\n\n // Permutations\n i = mod(i, 289.0 );\n vec4 p = permute( permute( permute(\n i.z + vec4(0.0, i1.z, i2.z, 1.0 ))\n + i.y + vec4(0.0, i1.y, i2.y, 1.0 ))\n + i.x + vec4(0.0, i1.x, i2.x, 1.0 ));\n\n // Gradients\n // ( N*N points uniformly over a square, mapped onto an octahedron.)\n float n_ = 1.0/7.0; // N=7\n vec3 ns = n_ * D.wyz - D.xzx;\n\n vec4 j = p - 49.0 * floor(p * ns.z *ns.z); // mod(p,N*N)\n\n vec4 x_ = floor(j * ns.z);\n vec4 y_ = floor(j - 7.0 * x_ ); // mod(j,N)\n\n vec4 x = x_ *ns.x + ns.yyyy;\n vec4 y = y_ *ns.x + ns.yyyy;\n vec4 h = 1.0 - abs(x) - abs(y);\n\n vec4 b0 = vec4( x.xy, y.xy );\n vec4 b1 = vec4( x.zw, y.zw );\n\n vec4 s0 = floor(b0)*2.0 + 1.0;\n vec4 s1 = floor(b1)*2.0 + 1.0;\n vec4 sh = -step(h, vec4(0.0));\n\n vec4 a0 = b0.xzyw + s0.xzyw*sh.xxyy ;\n vec4 a1 = b1.xzyw + s1.xzyw*sh.zzww ;\n\n vec3 p0 = vec3(a0.xy,h.x);\n vec3 p1 = vec3(a0.zw,h.y);\n vec3 p2 = vec3(a1.xy,h.z);\n vec3 p3 = vec3(a1.zw,h.w);\n\n //Normalise gradients\n vec4 norm = taylorInvSqrt(vec4(dot(p0,p0), dot(p1,p1), dot(p2, p2), dot(p3,p3)));\n p0 *= norm.x;\n p1 *= norm.y;\n p2 *= norm.z;\n p3 *= norm.w;\n\n // Mix final noise value\n vec4 m = max(0.6 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);\n m = m * m;\n return 42.0 * dot( m*m, vec4( dot(p0,x0), dot(p1,x1),\n dot(p2,x2), dot(p3,x3) ) );\n }\n `},_rgbToHsv:{type:"util",glsl:`vec3 _rgbToHsv(vec3 c){\n vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));\n vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n\n float d = q.x - min(q.w, q.y);\n float e = 1.0e-10;\n return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);\n }`},_hsvToRgb:{type:"util",glsl:`vec3 _hsvToRgb(vec3 c){\n vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);\n return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);\n }`}}},{}],99:[function(require,module,exports){const Webcam=require("./lib/webcam.js");const Screen=require("./lib/screenmedia.js");class HydraSource{constructor({regl:regl,width:width,height:height,pb:pb,label:label=""}){this.label=label;this.regl=regl;this.src=null;this.dynamic=true;this.width=width;this.height=height;this.tex=this.regl.texture({shape:[1,1]});this.pb=pb}init(opts,params){if("src"in opts){this.src=opts.src;this.tex=this.regl.texture({data:this.src,...params})}if("dynamic"in opts)this.dynamic=opts.dynamic}initCam(index,params){const self=this;Webcam(index).then((response=>{self.src=response.video;self.dynamic=true;self.tex=self.regl.texture({data:self.src,...params})})).catch((err=>console.log("could not get camera",err)))}initVideo(url="",params){const vid=document.createElement("video");vid.crossOrigin="anonymous";vid.autoplay=true;vid.loop=true;vid.muted=true;const onload=vid.addEventListener("loadeddata",(()=>{this.src=vid;vid.play();this.tex=this.regl.texture({data:this.src,...params});this.dynamic=true}));vid.src=url}initImage(url="",params){const img=document.createElement("img");img.crossOrigin="anonymous";img.src=url;img.onload=()=>{this.src=img;this.dynamic=false;this.tex=this.regl.texture({data:this.src,...params})}}initStream(streamName,params){let self=this;if(streamName&&this.pb){this.pb.initSource(streamName);this.pb.on("got video",(function(nick,video){if(nick===streamName){self.src=video;self.dynamic=true;self.tex=self.regl.texture({data:self.src,...params})}}))}}initScreen(index=0,params){const self=this;Screen().then((function(response){self.src=response.video;self.tex=self.regl.texture({data:self.src,...params});self.dynamic=true})).catch((err=>console.log("could not get screen",err)))}resize(width,height){this.width=width;this.height=height}clear(){if(this.src&&this.src.srcObject){if(this.src.srcObject.getTracks){this.src.srcObject.getTracks().forEach((track=>track.stop()))}}this.src=null;this.tex=this.regl.texture({shape:[1,1]})}tick(time){if(this.src!==null&&this.dynamic===true){if(this.src.videoWidth&&this.src.videoWidth!==this.tex.width){console.log(this.src.videoWidth,this.src.videoHeight,this.tex.width,this.tex.height);this.tex.resize(this.src.videoWidth,this.src.videoHeight)}if(this.src.width&&this.src.width!==this.tex.width){this.tex.resize(this.src.width,this.src.height)}this.tex.subimage(this.src)}}getTexture(){return this.tex}}module.exports=HydraSource},{"./lib/screenmedia.js":106,"./lib/webcam.js":108}],100:[function(require,module,exports){var easing=require("./easing-functions.js");var map=(num,in_min,in_max,out_min,out_max)=>(num-in_min)*(out_max-out_min)/(in_max-in_min)+out_min;module.exports={init:()=>{Array.prototype.fast=function(speed=1){this._speed=speed;return this};Array.prototype.smooth=function(smooth=1){this._smooth=smooth;return this};Array.prototype.ease=function(ease="linear"){if(typeof ease=="function"){this._smooth=1;this._ease=ease}else if(easing[ease]){this._smooth=1;this._ease=easing[ease]}return this};Array.prototype.offset=function(offset=.5){this._offset=offset%1;return this};Array.prototype.fit=function(low=0,high=1){let lowest=Math.min(...this);let highest=Math.max(...this);var newArr=this.map((num=>map(num,lowest,highest,low,high)));newArr._speed=this._speed;newArr._smooth=this._smooth;newArr._ease=this._ease;return newArr}},getValue:(arr=[])=>({time:time,bpm:bpm})=>{let speed=arr._speed?arr._speed:1;let smooth=arr._smooth?arr._smooth:0;let index=time*speed*(bpm/60)+(arr._offset||0);if(smooth!==0){let ease=arr._ease?arr._ease:easing["linear"];let _index=index-smooth/2;let currValue=arr[Math.floor(_index%arr.length)];let nextValue=arr[Math.floor((_index+1)%arr.length)];let t=Math.min(_index%1/smooth,1);return ease(t)*(nextValue-currValue)+currValue}else{return arr[Math.floor(index%arr.length)]}}}},{"./easing-functions.js":102}],101:[function(require,module,exports){const Meyda=require("meyda");class Audio{constructor({numBins:numBins=4,cutoff:cutoff=2,smooth:smooth=.4,max:max=15,scale:scale=10,isDrawing:isDrawing=false}){this.vol=0;this.scale=scale;this.max=max;this.cutoff=cutoff;this.smooth=smooth;this.setBins(numBins);this.beat={holdFrames:20,threshold:40,_cutoff:0,decay:.98,_framesSinceBeat:0};this.onBeat=()=>{};this.canvas=document.createElement("canvas");this.canvas.width=100;this.canvas.height=80;this.canvas.style.width="100px";this.canvas.style.height="80px";this.canvas.style.position="absolute";this.canvas.style.right="0px";this.canvas.style.bottom="0px";document.body.appendChild(this.canvas);this.isDrawing=isDrawing;this.ctx=this.canvas.getContext("2d");this.ctx.fillStyle="#DFFFFF";this.ctx.strokeStyle="#0ff";this.ctx.lineWidth=.5;if(window.navigator.mediaDevices){window.navigator.mediaDevices.getUserMedia({video:false,audio:true}).then((stream=>{this.stream=stream;this.context=new AudioContext;let audio_stream=this.context.createMediaStreamSource(stream);this.meyda=Meyda.createMeydaAnalyzer({audioContext:this.context,source:audio_stream,featureExtractors:["loudness"]})})).catch((err=>console.log("ERROR",err)))}}detectBeat(level){if(level>this.beat._cutoff&&level>this.beat.threshold){this.onBeat();this.beat._cutoff=level*1.2;this.beat._framesSinceBeat=0}else{if(this.beat._framesSinceBeat<=this.beat.holdFrames){this.beat._framesSinceBeat++}else{this.beat._cutoff*=this.beat.decay;this.beat._cutoff=Math.max(this.beat._cutoff,this.beat.threshold)}}}tick(){if(this.meyda){var features=this.meyda.get();if(features&&features!==null){this.vol=features.loudness.total;this.detectBeat(this.vol);const reducer=(accumulator,currentValue)=>accumulator+currentValue;let spacing=Math.floor(features.loudness.specific.length/this.bins.length);this.prevBins=this.bins.slice(0);this.bins=this.bins.map(((bin,index)=>features.loudness.specific.slice(index*spacing,(index+1)*spacing).reduce(reducer))).map(((bin,index)=>bin*(1-this.settings[index].smooth)+this.prevBins[index]*this.settings[index].smooth));this.fft=this.bins.map(((bin,index)=>Math.max(0,(bin-this.settings[index].cutoff)/this.settings[index].scale)));if(this.isDrawing)this.draw()}}}setCutoff(cutoff){this.cutoff=cutoff;this.settings=this.settings.map((el=>{el.cutoff=cutoff;return el}))}setSmooth(smooth){this.smooth=smooth;this.settings=this.settings.map((el=>{el.smooth=smooth;return el}))}setBins(numBins){this.bins=Array(numBins).fill(0);this.prevBins=Array(numBins).fill(0);this.fft=Array(numBins).fill(0);this.settings=Array(numBins).fill(0).map((()=>({cutoff:this.cutoff,scale:this.scale,smooth:this.smooth})));this.bins.forEach(((bin,index)=>{window["a"+index]=(scale=1,offset=0)=>()=>a.fft[index]*scale+offset}))}setScale(scale){this.scale=scale;this.settings=this.settings.map((el=>{el.scale=scale;return el}))}setMax(max){this.max=max;console.log("set max is deprecated")}hide(){this.isDrawing=false;this.canvas.style.display="none"}show(){this.isDrawing=true;this.canvas.style.display="block"}draw(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);var spacing=this.canvas.width/this.bins.length;var scale=this.canvas.height/(this.max*2);this.bins.forEach(((bin,index)=>{var height=bin*scale;this.ctx.fillRect(index*spacing,this.canvas.height-height,spacing,height);var y=this.canvas.height-scale*this.settings[index].cutoff;this.ctx.beginPath();this.ctx.moveTo(index*spacing,y);this.ctx.lineTo((index+1)*spacing,y);this.ctx.stroke();var yMax=this.canvas.height-scale*(this.settings[index].scale+this.settings[index].cutoff);this.ctx.beginPath();this.ctx.moveTo(index*spacing,yMax);this.ctx.lineTo((index+1)*spacing,yMax);this.ctx.stroke()}))}}module.exports=Audio},{meyda:140}],102:[function(require,module,exports){module.exports={linear:function(t){return t},easeInQuad:function(t){return t*t},easeOutQuad:function(t){return t*(2-t)},easeInOutQuad:function(t){return t<.5?2*t*t:-1+(4-2*t)*t},easeInCubic:function(t){return t*t*t},easeOutCubic:function(t){return--t*t*t+1},easeInOutCubic:function(t){return t<.5?4*t*t*t:(t-1)*(2*t-2)*(2*t-2)+1},easeInQuart:function(t){return t*t*t*t},easeOutQuart:function(t){return 1- --t*t*t*t},easeInOutQuart:function(t){return t<.5?8*t*t*t*t:1-8*--t*t*t*t},easeInQuint:function(t){return t*t*t*t*t},easeOutQuint:function(t){return 1+--t*t*t*t*t},easeInOutQuint:function(t){return t<.5?16*t*t*t*t*t:1+16*--t*t*t*t*t},sin:function(t){return(1+Math.sin(Math.PI*t-Math.PI/2))/2}}},{}],103:[function(require,module,exports){"use strict";function mouseButtons(ev){if(typeof ev==="object"){if("buttons"in ev){return ev.buttons}else if("which"in ev){var b=ev.which;if(b===2){return 4}else if(b===3){return 2}else if(b>0){return 1<=0){return 1<{var initialCode=``;var sandbox=createSandbox(initialCode);var addToContext=(name,object)=>{initialCode+=`\n var ${name} = ${object}\n `;sandbox=createSandbox(initialCode)};return{addToContext:addToContext,eval:code=>sandbox.eval(code)};function createSandbox(initial){eval(initial);var localEval=function(code){eval(code)};return{eval:localEval}}}},{}],106:[function(require,module,exports){module.exports=function(options){return new Promise((function(resolve,reject){navigator.mediaDevices.getDisplayMedia(options).then((stream=>{const video=document.createElement("video");video.srcObject=stream;video.addEventListener("loadedmetadata",(()=>{video.play();resolve({video:video})}))})).catch((err=>reject(err)))}))}},{}],107:[function(require,module,exports){class VideoRecorder{constructor(stream){this.mediaSource=new MediaSource;this.stream=stream;this.output=document.createElement("video");this.output.autoplay=true;this.output.loop=true;let self=this;this.mediaSource.addEventListener("sourceopen",(()=>{console.log("MediaSource opened");self.sourceBuffer=self.mediaSource.addSourceBuffer('video/webm; codecs="vp8"');console.log("Source buffer: ",sourceBuffer)}))}start(){let options={mimeType:"video/webm;codecs=vp9"};this.recordedBlobs=[];try{this.mediaRecorder=new MediaRecorder(this.stream,options)}catch(e0){console.log("Unable to create MediaRecorder with options Object: ",e0);try{options={mimeType:"video/webm,codecs=vp9"};this.mediaRecorder=new MediaRecorder(this.stream,options)}catch(e1){console.log("Unable to create MediaRecorder with options Object: ",e1);try{options="video/vp8";this.mediaRecorder=new MediaRecorder(this.stream,options)}catch(e2){alert("MediaRecorder is not supported by this browser.\n\n"+"Try Firefox 29 or later, or Chrome 47 or later, "+"with Enable experimental Web Platform features enabled from chrome://flags.");console.error("Exception while creating MediaRecorder:",e2);return}}}console.log("Created MediaRecorder",this.mediaRecorder,"with options",options);this.mediaRecorder.onstop=this._handleStop.bind(this);this.mediaRecorder.ondataavailable=this._handleDataAvailable.bind(this);this.mediaRecorder.start(100);console.log("MediaRecorder started",this.mediaRecorder)}stop(){this.mediaRecorder.stop()}_handleStop(){const blob=new Blob(this.recordedBlobs,{type:this.mediaRecorder.mimeType});const url=window.URL.createObjectURL(blob);this.output.src=url;const a=document.createElement("a");a.style.display="none";a.href=url;let d=new Date;a.download=`hydra-${d.getFullYear()}-${d.getMonth()+1}-${d.getDate()}-${d.getHours()}.${d.getMinutes()}.${d.getSeconds()}.webm`;document.body.appendChild(a);a.click();setTimeout((()=>{document.body.removeChild(a);window.URL.revokeObjectURL(url)}),300)}_handleDataAvailable(event){if(event.data&&event.data.size>0){this.recordedBlobs.push(event.data)}}}module.exports=VideoRecorder},{}],108:[function(require,module,exports){module.exports=function(deviceId){return navigator.mediaDevices.enumerateDevices().then((devices=>devices.filter((devices=>devices.kind==="videoinput")))).then((cameras=>{let constraints={audio:false,video:true};if(cameras[deviceId]){constraints["video"]={deviceId:{exact:cameras[deviceId].deviceId}}}return window.navigator.mediaDevices.getUserMedia(constraints)})).then((stream=>{const video=document.createElement("video");video.setAttribute("autoplay","");video.setAttribute("muted","");video.setAttribute("playsinline","");video.srcObject=stream;return new Promise(((resolve,reject)=>{video.addEventListener("loadedmetadata",(()=>{video.play().then((()=>resolve({video:video})))}))}))})).catch(console.log.bind(console))}},{}],109:[function(require,module,exports){var Output=function({regl:regl,precision:precision,label:label="",width:width,height:height}){this.regl=regl;this.precision=precision;this.label=label;this.positionBuffer=this.regl.buffer([[-2,0],[0,-2],[2,2]]);this.draw=()=>{};this.init();this.pingPongIndex=0;this.fbos=Array(2).fill().map((()=>this.regl.framebuffer({color:this.regl.texture({mag:"nearest",width:width,height:height,format:"rgba"}),depthStencil:false})))};Output.prototype.resize=function(width,height){this.fbos.forEach((fbo=>{fbo.resize(width,height)}))};Output.prototype.getCurrent=function(){return this.fbos[this.pingPongIndex]};Output.prototype.getTexture=function(){var index=this.pingPongIndex?0:1;return this.fbos[index]};Output.prototype.init=function(){this.transformIndex=0;this.fragHeader=`\n precision ${this.precision} float;\n\n uniform float time;\n varying vec2 uv;\n `;this.fragBody=``;this.vert=`\n precision ${this.precision} float;\n attribute vec2 position;\n varying vec2 uv;\n\n void main () {\n uv = position;\n gl_Position = vec4(2.0 * position - 1.0, 0, 1);\n }`;this.attributes={position:this.positionBuffer};this.uniforms={time:this.regl.prop("time"),resolution:this.regl.prop("resolution")};this.frag=`\n ${this.fragHeader}\n\n void main () {\n vec4 c = vec4(0, 0, 0, 0);\n vec2 st = uv;\n ${this.fragBody}\n gl_FragColor = c;\n }\n `;return this};Output.prototype.render=function(passes){let pass=passes[0];var self=this;var uniforms=Object.assign(pass.uniforms,{prevBuffer:()=>self.fbos[self.pingPongIndex]});self.draw=self.regl({frag:pass.frag,vert:self.vert,attributes:self.attributes,uniforms:uniforms,count:3,framebuffer:()=>{self.pingPongIndex=self.pingPongIndex?0:1;return self.fbos[self.pingPongIndex]}})};Output.prototype.tick=function(props){this.draw(props)};module.exports=Output},{}],110:[function(require,module,exports){module.exports=attributeToProperty;var transform={class:"className",for:"htmlFor","http-equiv":"httpEquiv"};function attributeToProperty(h){return function(tagName,attrs,children){for(var attr in attrs){if(attr in transform){attrs[transform[attr]]=attrs[attr];delete attrs[attr]}}return h(tagName,attrs,children)}}},{}],111:[function(require,module,exports){var attrToProp=require("hyperscript-attribute-to-property");var VAR=0,TEXT=1,OPEN=2,CLOSE=3,ATTR=4;var ATTR_KEY=5,ATTR_KEY_W=6;var ATTR_VALUE_W=7,ATTR_VALUE=8;var ATTR_VALUE_SQ=9,ATTR_VALUE_DQ=10;var ATTR_EQ=11,ATTR_BREAK=12;var COMMENT=13;module.exports=function(h,opts){if(!opts)opts={};var concat=opts.concat||function(a,b){return String(a)+String(b)};if(opts.attrToProp!==false){h=attrToProp(h)}return function(strings){var state=TEXT,reg="";var arglen=arguments.length;var parts=[];for(var i=0;i1){stack.pop();stack[stack.length-1][0][2][ix]=h(cur[0],cur[1],cur[2].length?cur[2]:undefined)}}else if(s===OPEN){var c=[p[1],{},[]];cur[2].push(c);stack.push([c,cur[2].length-1])}else if(s===ATTR_KEY||s===VAR&&p[1]===ATTR_KEY){var key="";var copyKey;for(;i1&&/^\s*$/.test(tree[2][0])){tree[2].shift()}if(tree[2].length>2||tree[2].length===2&&/\S/.test(tree[2][1])){if(opts.createFragment)return opts.createFragment(tree[2]);throw new Error("multiple root elements must be wrapped in an enclosing tag")}if(Array.isArray(tree[2][0])&&typeof tree[2][0][0]==="string"&&Array.isArray(tree[2][0][2])){tree[2][0]=h(tree[2][0][0],tree[2][0][1],tree[2][0][2])}return tree[2][0];function parse(str){var res=[];if(state===ATTR_VALUE_W)state=ATTR;for(var i=0;i"&&!quot(state)&&state!==COMMENT){if(state===OPEN&®.length){res.push([OPEN,reg])}else if(state===ATTR_KEY){res.push([ATTR_KEY,reg])}else if(state===ATTR_VALUE&®.length){res.push([ATTR_VALUE,reg])}res.push([CLOSE]);reg="";state=TEXT}else if(state===COMMENT&&/-$/.test(reg)&&c==="-"){if(opts.comments){res.push([ATTR_VALUE,reg.substr(0,reg.length-1)])}reg="";state=TEXT}else if(state===OPEN&&/^!--$/.test(reg)){if(opts.comments){res.push([OPEN,reg],[ATTR_KEY,"comment"],[ATTR_EQ])}reg=c;state=COMMENT}else if(state===TEXT||state===COMMENT){reg+=c}else if(state===OPEN&&c==="/"&®.length){}else if(state===OPEN&&/\s/.test(c)){if(reg.length){res.push([OPEN,reg])}reg="";state=ATTR}else if(state===OPEN){reg+=c}else if(state===ATTR&&/[^\s"'=/]/.test(c)){state=ATTR_KEY;reg=c}else if(state===ATTR&&/\s/.test(c)){if(reg.length)res.push([ATTR_KEY,reg]);res.push([ATTR_BREAK])}else if(state===ATTR_KEY&&/\s/.test(c)){res.push([ATTR_KEY,reg]);reg="";state=ATTR_KEY_W}else if(state===ATTR_KEY&&c==="="){res.push([ATTR_KEY,reg],[ATTR_EQ]);reg="";state=ATTR_VALUE_W}else if(state===ATTR_KEY){reg+=c}else if((state===ATTR_KEY_W||state===ATTR)&&c==="="){res.push([ATTR_EQ]);state=ATTR_VALUE_W}else if((state===ATTR_KEY_W||state===ATTR)&&!/\s/.test(c)){res.push([ATTR_BREAK]);if(/[\w-]/.test(c)){reg+=c;state=ATTR_KEY}else state=ATTR}else if(state===ATTR_VALUE_W&&c==='"'){state=ATTR_VALUE_DQ}else if(state===ATTR_VALUE_W&&c==="'"){state=ATTR_VALUE_SQ}else if(state===ATTR_VALUE_DQ&&c==='"'){res.push([ATTR_VALUE,reg],[ATTR_BREAK]);reg="";state=ATTR}else if(state===ATTR_VALUE_SQ&&c==="'"){res.push([ATTR_VALUE,reg],[ATTR_BREAK]);reg="";state=ATTR}else if(state===ATTR_VALUE_W&&!/\s/.test(c)){state=ATTR_VALUE;i--}else if(state===ATTR_VALUE&&/\s/.test(c)){res.push([ATTR_VALUE,reg],[ATTR_BREAK]);reg="";state=ATTR}else if(state===ATTR_VALUE||state===ATTR_VALUE_SQ||state===ATTR_VALUE_DQ){reg+=c}}if(state===TEXT&®.length){res.push([TEXT,reg]);reg=""}else if(state===ATTR_VALUE&®.length){res.push([ATTR_VALUE,reg]);reg=""}else if(state===ATTR_VALUE_DQ&®.length){res.push([ATTR_VALUE,reg]);reg=""}else if(state===ATTR_VALUE_SQ&®.length){res.push([ATTR_VALUE,reg]);reg=""}else if(state===ATTR_KEY){res.push([ATTR_KEY,reg]);reg=""}return res}};function strfn(x){if(typeof x==="function")return x;else if(typeof x==="string")return x;else if(x&&typeof x==="object")return x;else if(x===null||x===undefined)return x;else return concat("",x)}};function quot(state){return state===ATTR_VALUE_SQ||state===ATTR_VALUE_DQ}var closeRE=RegExp("^("+["area","base","basefont","bgsound","br","col","command","embed","frame","hr","img","input","isindex","keygen","link","meta","param","source","track","wbr","!--","animate","animateTransform","circle","cursor","desc","ellipse","feBlend","feColorMatrix","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","font-face-format","font-face-name","font-face-uri","glyph","glyphRef","hkern","image","line","missing-glyph","mpath","path","polygon","polyline","rect","set","stop","tref","use","view","vkern"].join("|")+")(?:[.#][a-zA-Z0-9-￿_:-]+)*$");function selfClosing(tag){return closeRE.test(tag)}},{"hyperscript-attribute-to-property":110}],112:[function(require,module,exports){"use strict";var _classCallCheck=require("@babel/runtime/helpers/classCallCheck");var _createClass=require("@babel/runtime/helpers/createClass");function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var _classCallCheck__default=_interopDefaultLegacy(_classCallCheck);var _createClass__default=_interopDefaultLegacy(_createClass);var arr=[];var each=arr.forEach;var slice=arr.slice;function defaults(obj){each.call(slice.call(arguments,1),(function(source){if(source){for(var prop in source){if(obj[prop]===undefined)obj[prop]=source[prop]}}}));return obj}var fieldContentRegExp=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;var serializeCookie=function serializeCookie(name,val,options){var opt=options||{};opt.path=opt.path||"/";var value=encodeURIComponent(val);var str=name+"="+value;if(opt.maxAge>0){var maxAge=opt.maxAge-0;if(isNaN(maxAge))throw new Error("maxAge should be a Number");str+="; Max-Age="+Math.floor(maxAge)}if(opt.domain){if(!fieldContentRegExp.test(opt.domain)){throw new TypeError("option domain is invalid")}str+="; Domain="+opt.domain}if(opt.path){if(!fieldContentRegExp.test(opt.path)){throw new TypeError("option path is invalid")}str+="; Path="+opt.path}if(opt.expires){if(typeof opt.expires.toUTCString!=="function"){throw new TypeError("option expires is invalid")}str+="; Expires="+opt.expires.toUTCString()}if(opt.httpOnly)str+="; HttpOnly";if(opt.secure)str+="; Secure";if(opt.sameSite){var sameSite=typeof opt.sameSite==="string"?opt.sameSite.toLowerCase():opt.sameSite;switch(sameSite){case true:str+="; SameSite=Strict";break;case"lax":str+="; SameSite=Lax";break;case"strict":str+="; SameSite=Strict";break;case"none":str+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}}return str};var cookie={create:function create(name,value,minutes,domain){var cookieOptions=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{path:"/",sameSite:"strict"};if(minutes){cookieOptions.expires=new Date;cookieOptions.expires.setTime(cookieOptions.expires.getTime()+minutes*60*1e3)}if(domain)cookieOptions.domain=domain;document.cookie=serializeCookie(name,encodeURIComponent(value),cookieOptions)},read:function read(name){var nameEQ=name+"=";var ca=document.cookie.split(";");for(var i=0;i0){var key=params[i].substring(0,pos);if(key===options.lookupQuerystring){found=params[i].substring(pos+1)}}}}return found}};var hasLocalStorageSupport=null;var localStorageAvailable=function localStorageAvailable(){if(hasLocalStorageSupport!==null)return hasLocalStorageSupport;try{hasLocalStorageSupport=window!=="undefined"&&window.localStorage!==null;var testKey="i18next.translate.boo";window.localStorage.setItem(testKey,"foo");window.localStorage.removeItem(testKey)}catch(e){hasLocalStorageSupport=false}return hasLocalStorageSupport};var localStorage={name:"localStorage",lookup:function lookup(options){var found;if(options.lookupLocalStorage&&localStorageAvailable()){var lng=window.localStorage.getItem(options.lookupLocalStorage);if(lng)found=lng}return found},cacheUserLanguage:function cacheUserLanguage(lng,options){if(options.lookupLocalStorage&&localStorageAvailable()){window.localStorage.setItem(options.lookupLocalStorage,lng)}}};var hasSessionStorageSupport=null;var sessionStorageAvailable=function sessionStorageAvailable(){if(hasSessionStorageSupport!==null)return hasSessionStorageSupport;try{hasSessionStorageSupport=window!=="undefined"&&window.sessionStorage!==null;var testKey="i18next.translate.boo";window.sessionStorage.setItem(testKey,"foo");window.sessionStorage.removeItem(testKey)}catch(e){hasSessionStorageSupport=false}return hasSessionStorageSupport};var sessionStorage={name:"sessionStorage",lookup:function lookup(options){var found;if(options.lookupSessionStorage&&sessionStorageAvailable()){var lng=window.sessionStorage.getItem(options.lookupSessionStorage);if(lng)found=lng}return found},cacheUserLanguage:function cacheUserLanguage(lng,options){if(options.lookupSessionStorage&&sessionStorageAvailable()){window.sessionStorage.setItem(options.lookupSessionStorage,lng)}}};var navigator$1={name:"navigator",lookup:function lookup(options){var found=[];if(typeof navigator!=="undefined"){if(navigator.languages){for(var i=0;i0?found:undefined}};var htmlTag={name:"htmlTag",lookup:function lookup(options){var found;var htmlTag=options.htmlTag||(typeof document!=="undefined"?document.documentElement:null);if(htmlTag&&typeof htmlTag.getAttribute==="function"){found=htmlTag.getAttribute("lang")}return found}};var path={name:"path",lookup:function lookup(options){var found;if(typeof window!=="undefined"){var language=window.location.pathname.match(/\/([a-zA-Z-]*)/g);if(language instanceof Array){if(typeof options.lookupFromPathIndex==="number"){if(typeof language[options.lookupFromPathIndex]!=="string"){return undefined}found=language[options.lookupFromPathIndex].replace("/","")}else{found=language[0].replace("/","")}}}return found}};var subdomain={name:"subdomain",lookup:function lookup(options){var found;if(typeof window!=="undefined"){var language=window.location.href.match(/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/gi);if(language instanceof Array){if(typeof options.lookupFromSubdomainIndex==="number"){found=language[options.lookupFromSubdomainIndex].replace("http://","").replace("https://","").replace(".","")}else{found=language[0].replace("http://","").replace("https://","").replace(".","")}}}return found}};function getDefaults(){return{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"]}}var Browser=function(){function Browser(services){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck__default["default"](this,Browser);this.type="languageDetector";this.detectors={};this.init(services,options)}_createClass__default["default"](Browser,[{key:"init",value:function init(services){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var i18nOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};this.services=services;this.options=defaults(options,this.options||{},getDefaults());if(this.options.lookupFromUrlIndex)this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex;this.i18nOptions=i18nOptions;this.addDetector(cookie$1);this.addDetector(querystring);this.addDetector(localStorage);this.addDetector(sessionStorage);this.addDetector(navigator$1);this.addDetector(htmlTag);this.addDetector(path);this.addDetector(subdomain)}},{key:"addDetector",value:function addDetector(detector){this.detectors[detector.name]=detector}},{key:"detect",value:function detect(detectionOrder){var _this=this;if(!detectionOrder)detectionOrder=this.options.order;var detected=[];detectionOrder.forEach((function(detectorName){if(_this.detectors[detectorName]){var lookup=_this.detectors[detectorName].lookup(_this.options);if(lookup&&typeof lookup==="string")lookup=[lookup];if(lookup)detected=detected.concat(lookup)}}));if(this.services.languageUtils.getBestMatchFromCodes)return detected;return detected.length>0?detected[0]:null}},{key:"cacheUserLanguage",value:function cacheUserLanguage(lng,caches){var _this2=this;if(!caches)caches=this.options.caches;if(!caches)return;if(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(lng)>-1)return;caches.forEach((function(cacheName){if(_this2.detectors[cacheName])_this2.detectors[cacheName].cacheUserLanguage(lng,_this2.options)}))}}]);return Browser}();Browser.type="languageDetector";module.exports=Browser},{"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6}],113:[function(require,module,exports){"use strict";var _typeof=require("@babel/runtime/helpers/typeof");var _classCallCheck=require("@babel/runtime/helpers/classCallCheck");var _createClass=require("@babel/runtime/helpers/createClass");var _assertThisInitialized=require("@babel/runtime/helpers/assertThisInitialized");var _inherits=require("@babel/runtime/helpers/inherits");var _possibleConstructorReturn=require("@babel/runtime/helpers/possibleConstructorReturn");var _getPrototypeOf=require("@babel/runtime/helpers/getPrototypeOf");var _defineProperty=require("@babel/runtime/helpers/defineProperty");var _toArray=require("@babel/runtime/helpers/toArray");function _interopDefaultLegacy(e){return e&&typeof e==="object"&&"default"in e?e:{default:e}}var _typeof__default=_interopDefaultLegacy(_typeof);var _classCallCheck__default=_interopDefaultLegacy(_classCallCheck);var _createClass__default=_interopDefaultLegacy(_createClass);var _assertThisInitialized__default=_interopDefaultLegacy(_assertThisInitialized);var _inherits__default=_interopDefaultLegacy(_inherits);var _possibleConstructorReturn__default=_interopDefaultLegacy(_possibleConstructorReturn);var _getPrototypeOf__default=_interopDefaultLegacy(_getPrototypeOf);var _defineProperty__default=_interopDefaultLegacy(_defineProperty);var _toArray__default=_interopDefaultLegacy(_toArray);function ownKeys(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread(target){for(var i=1;i1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck__default["default"](this,Logger);this.init(concreteLogger,options)}_createClass__default["default"](Logger,[{key:"init",value:function init(concreteLogger){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};this.prefix=options.prefix||"i18next:";this.logger=concreteLogger||consoleLogger;this.options=options;this.debug=options.debug}},{key:"setDebug",value:function setDebug(bool){this.debug=bool}},{key:"log",value:function log(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}return this.forward(args,"log","",true)}},{key:"warn",value:function warn(){for(var _len2=arguments.length,args=new Array(_len2),_key2=0;_key2<_len2;_key2++){args[_key2]=arguments[_key2]}return this.forward(args,"warn","",true)}},{key:"error",value:function error(){for(var _len3=arguments.length,args=new Array(_len3),_key3=0;_key3<_len3;_key3++){args[_key3]=arguments[_key3]}return this.forward(args,"error","")}},{key:"deprecate",value:function deprecate(){for(var _len4=arguments.length,args=new Array(_len4),_key4=0;_key4<_len4;_key4++){args[_key4]=arguments[_key4]}return this.forward(args,"warn","WARNING DEPRECATED: ",true)}},{key:"forward",value:function forward(args,lvl,prefix,debugOnly){if(debugOnly&&!this.debug)return null;if(typeof args[0]==="string")args[0]="".concat(prefix).concat(this.prefix," ").concat(args[0]);return this.logger[lvl](args)}},{key:"create",value:function create(moduleName){return new Logger(this.logger,_objectSpread(_objectSpread({},{prefix:"".concat(this.prefix,":").concat(moduleName,":")}),this.options))}}]);return Logger}();var baseLogger=new Logger;var EventEmitter=function(){function EventEmitter(){_classCallCheck__default["default"](this,EventEmitter);this.observers={}}_createClass__default["default"](EventEmitter,[{key:"on",value:function on(events,listener){var _this=this;events.split(" ").forEach((function(event){_this.observers[event]=_this.observers[event]||[];_this.observers[event].push(listener)}));return this}},{key:"off",value:function off(event,listener){if(!this.observers[event])return;if(!listener){delete this.observers[event];return}this.observers[event]=this.observers[event].filter((function(l){return l!==listener}))}},{key:"emit",value:function emit(event){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key]}if(this.observers[event]){var cloned=[].concat(this.observers[event]);cloned.forEach((function(observer){observer.apply(void 0,args)}))}if(this.observers["*"]){var _cloned=[].concat(this.observers["*"]);_cloned.forEach((function(observer){observer.apply(observer,[event].concat(args))}))}}}]);return EventEmitter}();function defer(){var res;var rej;var promise=new Promise((function(resolve,reject){res=resolve;rej=reject}));promise.resolve=res;promise.reject=rej;return promise}function makeString(object){if(object==null)return"";return""+object}function copy(a,s,t){a.forEach((function(m){if(s[m])t[m]=s[m]}))}function getLastOfPath(object,path,Empty){function cleanKey(key){return key&&key.indexOf("###")>-1?key.replace(/###/g,"."):key}function canNotTraverseDeeper(){return!object||typeof object==="string"}var stack=typeof path!=="string"?[].concat(path):path.split(".");while(stack.length>1){if(canNotTraverseDeeper())return{};var key=cleanKey(stack.shift());if(!object[key]&&Empty)object[key]=new Empty;if(Object.prototype.hasOwnProperty.call(object,key)){object=object[key]}else{object={}}}if(canNotTraverseDeeper())return{};return{obj:object,k:cleanKey(stack.shift())}}function setPath(object,path,newValue){var _getLastOfPath=getLastOfPath(object,path,Object),obj=_getLastOfPath.obj,k=_getLastOfPath.k;obj[k]=newValue}function pushPath(object,path,newValue,concat){var _getLastOfPath2=getLastOfPath(object,path,Object),obj=_getLastOfPath2.obj,k=_getLastOfPath2.k;obj[k]=obj[k]||[];if(concat)obj[k]=obj[k].concat(newValue);if(!concat)obj[k].push(newValue)}function getPath(object,path){var _getLastOfPath3=getLastOfPath(object,path),obj=_getLastOfPath3.obj,k=_getLastOfPath3.k;if(!obj)return undefined;return obj[k]}function getPathWithDefaults(data,defaultData,key){var value=getPath(data,key);if(value!==undefined){return value}return getPath(defaultData,key)}function deepExtend(target,source,overwrite){for(var prop in source){if(prop!=="__proto__"&&prop!=="constructor"){if(prop in target){if(typeof target[prop]==="string"||target[prop]instanceof String||typeof source[prop]==="string"||source[prop]instanceof String){if(overwrite)target[prop]=source[prop]}else{deepExtend(target[prop],source[prop],overwrite)}}else{target[prop]=source[prop]}}}return target}function regexEscape(str){return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")}var _entityMap={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};function escape(data){if(typeof data==="string"){return data.replace(/[&<>"'\/]/g,(function(s){return _entityMap[s]}))}return data}var isIE10=typeof window!=="undefined"&&window.navigator&&window.navigator.userAgent&&window.navigator.userAgent.indexOf("MSIE")>-1;var chars=[" ",",","?","!",";"];function looksLikeObjectPath(key,nsSeparator,keySeparator){nsSeparator=nsSeparator||"";keySeparator=keySeparator||"";var possibleChars=chars.filter((function(c){return nsSeparator.indexOf(c)<0&&keySeparator.indexOf(c)<0}));if(possibleChars.length===0)return true;var r=new RegExp("(".concat(possibleChars.map((function(c){return c==="?"?"\\?":c})).join("|"),")"));var matched=!r.test(key);if(!matched){var ki=key.indexOf(keySeparator);if(ki>0&&!r.test(key.substring(0,ki))){matched=true}}return matched}function ownKeys$1(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread$1(target){for(var i=1;i2&&arguments[2]!==undefined?arguments[2]:".";if(!obj)return undefined;if(obj[path])return obj[path];var paths=path.split(keySeparator);var current=obj;for(var i=0;ii+j){j++;p=paths.slice(i,i+j).join(keySeparator);mix=current[p]}if(mix===undefined)return undefined;if(path.endsWith(p)){if(typeof mix==="string")return mix;if(p&&typeof mix[p]==="string")return mix[p]}var joinedPath=paths.slice(i+j).join(keySeparator);if(joinedPath)return deepFind(mix,joinedPath,keySeparator);return undefined}current=current[paths[i]]}return current}var ResourceStore=function(_EventEmitter){_inherits__default["default"](ResourceStore,_EventEmitter);var _super=_createSuper(ResourceStore);function ResourceStore(data){var _this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{ns:["translation"],defaultNS:"translation"};_classCallCheck__default["default"](this,ResourceStore);_this=_super.call(this);if(isIE10){EventEmitter.call(_assertThisInitialized__default["default"](_this))}_this.data=data||{};_this.options=options;if(_this.options.keySeparator===undefined){_this.options.keySeparator="."}if(_this.options.ignoreJSONStructure===undefined){_this.options.ignoreJSONStructure=true}return _this}_createClass__default["default"](ResourceStore,[{key:"addNamespaces",value:function addNamespaces(ns){if(this.options.ns.indexOf(ns)<0){this.options.ns.push(ns)}}},{key:"removeNamespaces",value:function removeNamespaces(ns){var index=this.options.ns.indexOf(ns);if(index>-1){this.options.ns.splice(index,1)}}},{key:"getResource",value:function getResource(lng,ns,key){var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};var keySeparator=options.keySeparator!==undefined?options.keySeparator:this.options.keySeparator;var ignoreJSONStructure=options.ignoreJSONStructure!==undefined?options.ignoreJSONStructure:this.options.ignoreJSONStructure;var path=[lng,ns];if(key&&typeof key!=="string")path=path.concat(key);if(key&&typeof key==="string")path=path.concat(keySeparator?key.split(keySeparator):key);if(lng.indexOf(".")>-1){path=lng.split(".")}var result=getPath(this.data,path);if(result||!ignoreJSONStructure||typeof key!=="string")return result;return deepFind(this.data&&this.data[lng]&&this.data[lng][ns],key,keySeparator)}},{key:"addResource",value:function addResource(lng,ns,key,value){var options=arguments.length>4&&arguments[4]!==undefined?arguments[4]:{silent:false};var keySeparator=this.options.keySeparator;if(keySeparator===undefined)keySeparator=".";var path=[lng,ns];if(key)path=path.concat(keySeparator?key.split(keySeparator):key);if(lng.indexOf(".")>-1){path=lng.split(".");value=ns;ns=path[1]}this.addNamespaces(ns);setPath(this.data,path,value);if(!options.silent)this.emit("added",lng,ns,key,value)}},{key:"addResources",value:function addResources(lng,ns,resources){var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{silent:false};for(var m in resources){if(typeof resources[m]==="string"||Object.prototype.toString.apply(resources[m])==="[object Array]")this.addResource(lng,ns,m,resources[m],{silent:true})}if(!options.silent)this.emit("added",lng,ns,resources)}},{key:"addResourceBundle",value:function addResourceBundle(lng,ns,resources,deep,overwrite){var options=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{silent:false};var path=[lng,ns];if(lng.indexOf(".")>-1){path=lng.split(".");deep=resources;resources=ns;ns=path[1]}this.addNamespaces(ns);var pack=getPath(this.data,path)||{};if(deep){deepExtend(pack,resources,overwrite)}else{pack=_objectSpread$1(_objectSpread$1({},pack),resources)}setPath(this.data,path,pack);if(!options.silent)this.emit("added",lng,ns,resources)}},{key:"removeResourceBundle",value:function removeResourceBundle(lng,ns){if(this.hasResourceBundle(lng,ns)){delete this.data[lng][ns]}this.removeNamespaces(ns);this.emit("removed",lng,ns)}},{key:"hasResourceBundle",value:function hasResourceBundle(lng,ns){return this.getResource(lng,ns)!==undefined}},{key:"getResourceBundle",value:function getResourceBundle(lng,ns){if(!ns)ns=this.options.defaultNS;if(this.options.compatibilityAPI==="v1")return _objectSpread$1(_objectSpread$1({},{}),this.getResource(lng,ns));return this.getResource(lng,ns)}},{key:"getDataByLanguage",value:function getDataByLanguage(lng){return this.data[lng]}},{key:"hasLanguageSomeTranslations",value:function hasLanguageSomeTranslations(lng){var data=this.getDataByLanguage(lng);var n=data&&Object.keys(data)||[];return!!n.find((function(v){return data[v]&&Object.keys(data[v]).length>0}))}},{key:"toJSON",value:function toJSON(){return this.data}}]);return ResourceStore}(EventEmitter);var postProcessor={processors:{},addPostProcessor:function addPostProcessor(module){this.processors[module.name]=module},handle:function handle(processors,value,key,options,translator){var _this=this;processors.forEach((function(processor){if(_this.processors[processor])value=_this.processors[processor].process(value,key,options,translator)}));return value}};function ownKeys$2(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread$2(target){for(var i=1;i1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck__default["default"](this,Translator);_this=_super.call(this);if(isIE10){EventEmitter.call(_assertThisInitialized__default["default"](_this))}copy(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],services,_assertThisInitialized__default["default"](_this));_this.options=options;if(_this.options.keySeparator===undefined){_this.options.keySeparator="."}_this.logger=baseLogger.create("translator");return _this}_createClass__default["default"](Translator,[{key:"changeLanguage",value:function changeLanguage(lng){if(lng)this.language=lng}},{key:"exists",value:function exists(key){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{interpolation:{}};if(key===undefined||key===null){return false}var resolved=this.resolve(key,options);return resolved&&resolved.res!==undefined}},{key:"extractFromKey",value:function extractFromKey(key,options){var nsSeparator=options.nsSeparator!==undefined?options.nsSeparator:this.options.nsSeparator;if(nsSeparator===undefined)nsSeparator=":";var keySeparator=options.keySeparator!==undefined?options.keySeparator:this.options.keySeparator;var namespaces=options.ns||this.options.defaultNS||[];var wouldCheckForNsInKey=nsSeparator&&key.indexOf(nsSeparator)>-1;var seemsNaturalLanguage=!this.options.userDefinedKeySeparator&&!options.keySeparator&&!this.options.userDefinedNsSeparator&&!options.nsSeparator&&!looksLikeObjectPath(key,nsSeparator,keySeparator);if(wouldCheckForNsInKey&&!seemsNaturalLanguage){var m=key.match(this.interpolator.nestingRegexp);if(m&&m.length>0){return{key:key,namespaces:namespaces}}var parts=key.split(nsSeparator);if(nsSeparator!==keySeparator||nsSeparator===keySeparator&&this.options.ns.indexOf(parts[0])>-1)namespaces=parts.shift();key=parts.join(keySeparator)}if(typeof namespaces==="string")namespaces=[namespaces];return{key:key,namespaces:namespaces}}},{key:"translate",value:function translate(keys,options,lastKey){var _this2=this;if(_typeof__default["default"](options)!=="object"&&this.options.overloadTranslationOptionHandler){options=this.options.overloadTranslationOptionHandler(arguments)}if(!options)options={};if(keys===undefined||keys===null)return"";if(!Array.isArray(keys))keys=[String(keys)];var keySeparator=options.keySeparator!==undefined?options.keySeparator:this.options.keySeparator;var _this$extractFromKey=this.extractFromKey(keys[keys.length-1],options),key=_this$extractFromKey.key,namespaces=_this$extractFromKey.namespaces;var namespace=namespaces[namespaces.length-1];var lng=options.lng||this.language;var appendNamespaceToCIMode=options.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(lng&&lng.toLowerCase()==="cimode"){if(appendNamespaceToCIMode){var nsSeparator=options.nsSeparator||this.options.nsSeparator;return namespace+nsSeparator+key}return key}var resolved=this.resolve(keys,options);var res=resolved&&resolved.res;var resUsedKey=resolved&&resolved.usedKey||key;var resExactUsedKey=resolved&&resolved.exactUsedKey||key;var resType=Object.prototype.toString.apply(res);var noObject=["[object Number]","[object Function]","[object RegExp]"];var joinArrays=options.joinArrays!==undefined?options.joinArrays:this.options.joinArrays;var handleAsObjectInI18nFormat=!this.i18nFormat||this.i18nFormat.handleAsObject;var handleAsObject=typeof res!=="string"&&typeof res!=="boolean"&&typeof res!=="number";if(handleAsObjectInI18nFormat&&res&&handleAsObject&&noObject.indexOf(resType)<0&&!(typeof joinArrays==="string"&&resType==="[object Array]")){if(!options.returnObjects&&!this.options.returnObjects){if(!this.options.returnedObjectHandler){this.logger.warn("accessing an object - but returnObjects options is not enabled!")}return this.options.returnedObjectHandler?this.options.returnedObjectHandler(resUsedKey,res,_objectSpread$2(_objectSpread$2({},options),{},{ns:namespaces})):"key '".concat(key," (").concat(this.language,")' returned an object instead of string.")}if(keySeparator){var resTypeIsArray=resType==="[object Array]";var copy=resTypeIsArray?[]:{};var newKeyToUse=resTypeIsArray?resExactUsedKey:resUsedKey;for(var m in res){if(Object.prototype.hasOwnProperty.call(res,m)){var deepKey="".concat(newKeyToUse).concat(keySeparator).concat(m);copy[m]=this.translate(deepKey,_objectSpread$2(_objectSpread$2({},options),{joinArrays:false,ns:namespaces}));if(copy[m]===deepKey)copy[m]=res[m]}}res=copy}}else if(handleAsObjectInI18nFormat&&typeof joinArrays==="string"&&resType==="[object Array]"){res=res.join(joinArrays);if(res)res=this.extendTranslation(res,keys,options,lastKey)}else{var usedDefault=false;var usedKey=false;var needsPluralHandling=options.count!==undefined&&typeof options.count!=="string";var hasDefaultValue=Translator.hasDefaultValue(options);var defaultValueSuffix=needsPluralHandling?this.pluralResolver.getSuffix(lng,options.count,options):"";var defaultValue=options["defaultValue".concat(defaultValueSuffix)]||options.defaultValue;if(!this.isValidLookup(res)&&hasDefaultValue){usedDefault=true;res=defaultValue}if(!this.isValidLookup(res)){usedKey=true;res=key}var missingKeyNoValueFallbackToKey=options.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey;var resForMissing=missingKeyNoValueFallbackToKey&&usedKey?undefined:res;var updateMissing=hasDefaultValue&&defaultValue!==res&&this.options.updateMissing;if(usedKey||usedDefault||updateMissing){this.logger.log(updateMissing?"updateKey":"missingKey",lng,namespace,key,updateMissing?defaultValue:res);if(keySeparator){var fk=this.resolve(key,_objectSpread$2(_objectSpread$2({},options),{},{keySeparator:false}));if(fk&&fk.res)this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}var lngs=[];var fallbackLngs=this.languageUtils.getFallbackCodes(this.options.fallbackLng,options.lng||this.language);if(this.options.saveMissingTo==="fallback"&&fallbackLngs&&fallbackLngs[0]){for(var i=0;i1&&arguments[1]!==undefined?arguments[1]:{};var found;var usedKey;var exactUsedKey;var usedLng;var usedNS;if(typeof keys==="string")keys=[keys];keys.forEach((function(k){if(_this4.isValidLookup(found))return;var extracted=_this4.extractFromKey(k,options);var key=extracted.key;usedKey=key;var namespaces=extracted.namespaces;if(_this4.options.fallbackNS)namespaces=namespaces.concat(_this4.options.fallbackNS);var needsPluralHandling=options.count!==undefined&&typeof options.count!=="string";var needsZeroSuffixLookup=needsPluralHandling&&!options.ordinal&&options.count===0&&_this4.pluralResolver.shouldUseIntlApi();var needsContextHandling=options.context!==undefined&&(typeof options.context==="string"||typeof options.context==="number")&&options.context!=="";var codes=options.lngs?options.lngs:_this4.languageUtils.toResolveHierarchy(options.lng||_this4.language,options.fallbackLng);namespaces.forEach((function(ns){if(_this4.isValidLookup(found))return;usedNS=ns;if(!checkedLoadedFor["".concat(codes[0],"-").concat(ns)]&&_this4.utils&&_this4.utils.hasLoadedNamespace&&!_this4.utils.hasLoadedNamespace(usedNS)){checkedLoadedFor["".concat(codes[0],"-").concat(ns)]=true;_this4.logger.warn('key "'.concat(usedKey,'" for languages "').concat(codes.join(", "),'" won\'t get resolved as namespace "').concat(usedNS,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")}codes.forEach((function(code){if(_this4.isValidLookup(found))return;usedLng=code;var finalKeys=[key];if(_this4.i18nFormat&&_this4.i18nFormat.addLookupKeys){_this4.i18nFormat.addLookupKeys(finalKeys,key,code,ns,options)}else{var pluralSuffix;if(needsPluralHandling)pluralSuffix=_this4.pluralResolver.getSuffix(code,options.count,options);var zeroSuffix="_zero";if(needsPluralHandling){finalKeys.push(key+pluralSuffix);if(needsZeroSuffixLookup){finalKeys.push(key+zeroSuffix)}}if(needsContextHandling){var contextKey="".concat(key).concat(_this4.options.contextSeparator).concat(options.context);finalKeys.push(contextKey);if(needsPluralHandling){finalKeys.push(contextKey+pluralSuffix);if(needsZeroSuffixLookup){finalKeys.push(contextKey+zeroSuffix)}}}}var possibleKey;while(possibleKey=finalKeys.pop()){if(!_this4.isValidLookup(found)){exactUsedKey=possibleKey;found=_this4.getResource(code,ns,possibleKey,options)}}}))}))}));return{res:found,usedKey:usedKey,exactUsedKey:exactUsedKey,usedLng:usedLng,usedNS:usedNS}}},{key:"isValidLookup",value:function isValidLookup(res){return res!==undefined&&!(!this.options.returnNull&&res===null)&&!(!this.options.returnEmptyString&&res==="")}},{key:"getResource",value:function getResource(code,ns,key){var options=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};if(this.i18nFormat&&this.i18nFormat.getResource)return this.i18nFormat.getResource(code,ns,key,options);return this.resourceStore.getResource(code,ns,key,options)}}],[{key:"hasDefaultValue",value:function hasDefaultValue(options){var prefix="defaultValue";for(var option in options){if(Object.prototype.hasOwnProperty.call(options,option)&&prefix===option.substring(0,prefix.length)&&undefined!==options[option]){return true}}return false}}]);return Translator}(EventEmitter);function capitalize(string){return string.charAt(0).toUpperCase()+string.slice(1)}var LanguageUtil=function(){function LanguageUtil(options){_classCallCheck__default["default"](this,LanguageUtil);this.options=options;this.supportedLngs=this.options.supportedLngs||false;this.logger=baseLogger.create("languageUtils")}_createClass__default["default"](LanguageUtil,[{key:"getScriptPartFromCode",value:function getScriptPartFromCode(code){if(!code||code.indexOf("-")<0)return null;var p=code.split("-");if(p.length===2)return null;p.pop();if(p[p.length-1].toLowerCase()==="x")return null;return this.formatLanguageCode(p.join("-"))}},{key:"getLanguagePartFromCode",value:function getLanguagePartFromCode(code){if(!code||code.indexOf("-")<0)return code;var p=code.split("-");return this.formatLanguageCode(p[0])}},{key:"formatLanguageCode",value:function formatLanguageCode(code){if(typeof code==="string"&&code.indexOf("-")>-1){var specialCases=["hans","hant","latn","cyrl","cans","mong","arab"];var p=code.split("-");if(this.options.lowerCaseLng){p=p.map((function(part){return part.toLowerCase()}))}else if(p.length===2){p[0]=p[0].toLowerCase();p[1]=p[1].toUpperCase();if(specialCases.indexOf(p[1].toLowerCase())>-1)p[1]=capitalize(p[1].toLowerCase())}else if(p.length===3){p[0]=p[0].toLowerCase();if(p[1].length===2)p[1]=p[1].toUpperCase();if(p[0]!=="sgn"&&p[2].length===2)p[2]=p[2].toUpperCase();if(specialCases.indexOf(p[1].toLowerCase())>-1)p[1]=capitalize(p[1].toLowerCase());if(specialCases.indexOf(p[2].toLowerCase())>-1)p[2]=capitalize(p[2].toLowerCase())}return p.join("-")}return this.options.cleanCode||this.options.lowerCaseLng?code.toLowerCase():code}},{key:"isSupportedCode",value:function isSupportedCode(code){if(this.options.load==="languageOnly"||this.options.nonExplicitSupportedLngs){code=this.getLanguagePartFromCode(code)}return!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(code)>-1}},{key:"getBestMatchFromCodes",value:function getBestMatchFromCodes(codes){var _this=this;if(!codes)return null;var found;codes.forEach((function(code){if(found)return;var cleanedLng=_this.formatLanguageCode(code);if(!_this.options.supportedLngs||_this.isSupportedCode(cleanedLng))found=cleanedLng}));if(!found&&this.options.supportedLngs){codes.forEach((function(code){if(found)return;var lngOnly=_this.getLanguagePartFromCode(code);if(_this.isSupportedCode(lngOnly))return found=lngOnly;found=_this.options.supportedLngs.find((function(supportedLng){if(supportedLng.indexOf(lngOnly)===0)return supportedLng}))}))}if(!found)found=this.getFallbackCodes(this.options.fallbackLng)[0];return found}},{key:"getFallbackCodes",value:function getFallbackCodes(fallbacks,code){if(!fallbacks)return[];if(typeof fallbacks==="function")fallbacks=fallbacks(code);if(typeof fallbacks==="string")fallbacks=[fallbacks];if(Object.prototype.toString.apply(fallbacks)==="[object Array]")return fallbacks;if(!code)return fallbacks["default"]||[];var found=fallbacks[code];if(!found)found=fallbacks[this.getScriptPartFromCode(code)];if(!found)found=fallbacks[this.formatLanguageCode(code)];if(!found)found=fallbacks[this.getLanguagePartFromCode(code)];if(!found)found=fallbacks["default"];return found||[]}},{key:"toResolveHierarchy",value:function toResolveHierarchy(code,fallbackCode){var _this2=this;var fallbackCodes=this.getFallbackCodes(fallbackCode||this.options.fallbackLng||[],code);var codes=[];var addCode=function addCode(c){if(!c)return;if(_this2.isSupportedCode(c)){codes.push(c)}else{_this2.logger.warn("rejecting language code not found in supportedLngs: ".concat(c))}};if(typeof code==="string"&&code.indexOf("-")>-1){if(this.options.load!=="languageOnly")addCode(this.formatLanguageCode(code));if(this.options.load!=="languageOnly"&&this.options.load!=="currentOnly")addCode(this.getScriptPartFromCode(code));if(this.options.load!=="currentOnly")addCode(this.getLanguagePartFromCode(code))}else if(typeof code==="string"){addCode(this.formatLanguageCode(code))}fallbackCodes.forEach((function(fc){if(codes.indexOf(fc)<0)addCode(_this2.formatLanguageCode(fc))}));return codes}}]);return LanguageUtil}();var sets=[{lngs:["ach","ak","am","arn","br","fil","gun","ln","mfe","mg","mi","oc","pt","pt-BR","tg","tl","ti","tr","uz","wa"],nr:[1,2],fc:1},{lngs:["af","an","ast","az","bg","bn","ca","da","de","dev","el","en","eo","es","et","eu","fi","fo","fur","fy","gl","gu","ha","hi","hu","hy","ia","it","kk","kn","ku","lb","mai","ml","mn","mr","nah","nap","nb","ne","nl","nn","no","nso","pa","pap","pms","ps","pt-PT","rm","sco","se","si","so","son","sq","sv","sw","ta","te","tk","ur","yo"],nr:[1,2],fc:2},{lngs:["ay","bo","cgg","fa","ht","id","ja","jbo","ka","km","ko","ky","lo","ms","sah","su","th","tt","ug","vi","wo","zh"],nr:[1],fc:3},{lngs:["be","bs","cnr","dz","hr","ru","sr","uk"],nr:[1,2,5],fc:4},{lngs:["ar"],nr:[0,1,2,3,11,100],fc:5},{lngs:["cs","sk"],nr:[1,2,5],fc:6},{lngs:["csb","pl"],nr:[1,2,5],fc:7},{lngs:["cy"],nr:[1,2,3,8],fc:8},{lngs:["fr"],nr:[1,2],fc:9},{lngs:["ga"],nr:[1,2,3,7,11],fc:10},{lngs:["gd"],nr:[1,2,3,20],fc:11},{lngs:["is"],nr:[1,2],fc:12},{lngs:["jv"],nr:[0,1],fc:13},{lngs:["kw"],nr:[1,2,3,4],fc:14},{lngs:["lt"],nr:[1,2,10],fc:15},{lngs:["lv"],nr:[1,2,0],fc:16},{lngs:["mk"],nr:[1,2],fc:17},{lngs:["mnk"],nr:[0,1,2],fc:18},{lngs:["mt"],nr:[1,2,11,20],fc:19},{lngs:["or"],nr:[2,1],fc:2},{lngs:["ro"],nr:[1,2,20],fc:20},{lngs:["sl"],nr:[5,1,2,3],fc:21},{lngs:["he","iw"],nr:[1,2,20,21],fc:22}];var _rulesPluralsTypes={1:function _(n){return Number(n>1)},2:function _(n){return Number(n!=1)},3:function _(n){return 0},4:function _(n){return Number(n%10==1&&n%100!=11?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2)},5:function _(n){return Number(n==0?0:n==1?1:n==2?2:n%100>=3&&n%100<=10?3:n%100>=11?4:5)},6:function _(n){return Number(n==1?0:n>=2&&n<=4?1:2)},7:function _(n){return Number(n==1?0:n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?1:2)},8:function _(n){return Number(n==1?0:n==2?1:n!=8&&n!=11?2:3)},9:function _(n){return Number(n>=2)},10:function _(n){return Number(n==1?0:n==2?1:n<7?2:n<11?3:4)},11:function _(n){return Number(n==1||n==11?0:n==2||n==12?1:n>2&&n<20?2:3)},12:function _(n){return Number(n%10!=1||n%100==11)},13:function _(n){return Number(n!==0)},14:function _(n){return Number(n==1?0:n==2?1:n==3?2:3)},15:function _(n){return Number(n%10==1&&n%100!=11?0:n%10>=2&&(n%100<10||n%100>=20)?1:2)},16:function _(n){return Number(n%10==1&&n%100!=11?0:n!==0?1:2)},17:function _(n){return Number(n==1||n%10==1&&n%100!=11?0:1)},18:function _(n){return Number(n==0?0:n==1?1:2)},19:function _(n){return Number(n==1?0:n==0||n%100>1&&n%100<11?1:n%100>10&&n%100<20?2:3)},20:function _(n){return Number(n==1?0:n==0||n%100>0&&n%100<20?1:2)},21:function _(n){return Number(n%100==1?1:n%100==2?2:n%100==3||n%100==4?3:0)},22:function _(n){return Number(n==1?0:n==2?1:(n<0||n>10)&&n%10==0?2:3)}};var deprecatedJsonVersions=["v1","v2","v3"];var suffixesOrder={zero:0,one:1,two:2,few:3,many:4,other:5};function createRules(){var rules={};sets.forEach((function(set){set.lngs.forEach((function(l){rules[l]={numbers:set.nr,plurals:_rulesPluralsTypes[set.fc]}}))}));return rules}var PluralResolver=function(){function PluralResolver(languageUtils){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};_classCallCheck__default["default"](this,PluralResolver);this.languageUtils=languageUtils;this.options=options;this.logger=baseLogger.create("pluralResolver");if((!this.options.compatibilityJSON||this.options.compatibilityJSON==="v4")&&(typeof Intl==="undefined"||!Intl.PluralRules)){this.options.compatibilityJSON="v3";this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.")}this.rules=createRules()}_createClass__default["default"](PluralResolver,[{key:"addRule",value:function addRule(lng,obj){this.rules[lng]=obj}},{key:"getRule",value:function getRule(code){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(this.shouldUseIntlApi()){try{return new Intl.PluralRules(code,{type:options.ordinal?"ordinal":"cardinal"})}catch(_unused){return}}return this.rules[code]||this.rules[this.languageUtils.getLanguagePartFromCode(code)]}},{key:"needsPlural",value:function needsPlural(code){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var rule=this.getRule(code,options);if(this.shouldUseIntlApi()){return rule&&rule.resolvedOptions().pluralCategories.length>1}return rule&&rule.numbers.length>1}},{key:"getPluralFormsOfKey",value:function getPluralFormsOfKey(code,key){var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};return this.getSuffixes(code,options).map((function(suffix){return"".concat(key).concat(suffix)}))}},{key:"getSuffixes",value:function getSuffixes(code){var _this=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var rule=this.getRule(code,options);if(!rule){return[]}if(this.shouldUseIntlApi()){return rule.resolvedOptions().pluralCategories.sort((function(pluralCategory1,pluralCategory2){return suffixesOrder[pluralCategory1]-suffixesOrder[pluralCategory2]})).map((function(pluralCategory){return"".concat(_this.options.prepend).concat(pluralCategory)}))}return rule.numbers.map((function(number){return _this.getSuffix(code,number,options)}))}},{key:"getSuffix",value:function getSuffix(code,count){var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var rule=this.getRule(code,options);if(rule){if(this.shouldUseIntlApi()){return"".concat(this.options.prepend).concat(rule.select(count))}return this.getSuffixRetroCompatible(rule,count)}this.logger.warn("no plural rule found for: ".concat(code));return""}},{key:"getSuffixRetroCompatible",value:function getSuffixRetroCompatible(rule,count){var _this2=this;var idx=rule.noAbs?rule.plurals(count):rule.plurals(Math.abs(count));var suffix=rule.numbers[idx];if(this.options.simplifyPluralSuffix&&rule.numbers.length===2&&rule.numbers[0]===1){if(suffix===2){suffix="plural"}else if(suffix===1){suffix=""}}var returnSuffix=function returnSuffix(){return _this2.options.prepend&&suffix.toString()?_this2.options.prepend+suffix.toString():suffix.toString()};if(this.options.compatibilityJSON==="v1"){if(suffix===1)return"";if(typeof suffix==="number")return"_plural_".concat(suffix.toString());return returnSuffix()}else if(this.options.compatibilityJSON==="v2"){return returnSuffix()}else if(this.options.simplifyPluralSuffix&&rule.numbers.length===2&&rule.numbers[0]===1){return returnSuffix()}return this.options.prepend&&idx.toString()?this.options.prepend+idx.toString():idx.toString()}},{key:"shouldUseIntlApi",value:function shouldUseIntlApi(){return!deprecatedJsonVersions.includes(this.options.compatibilityJSON)}}]);return PluralResolver}();function ownKeys$3(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread$3(target){for(var i=1;i0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck__default["default"](this,Interpolator);this.logger=baseLogger.create("interpolator");this.options=options;this.format=options.interpolation&&options.interpolation.format||function(value){return value};this.init(options)}_createClass__default["default"](Interpolator,[{key:"init",value:function init(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};if(!options.interpolation)options.interpolation={escapeValue:true};var iOpts=options.interpolation;this.escape=iOpts.escape!==undefined?iOpts.escape:escape;this.escapeValue=iOpts.escapeValue!==undefined?iOpts.escapeValue:true;this.useRawValueToEscape=iOpts.useRawValueToEscape!==undefined?iOpts.useRawValueToEscape:false;this.prefix=iOpts.prefix?regexEscape(iOpts.prefix):iOpts.prefixEscaped||"{{";this.suffix=iOpts.suffix?regexEscape(iOpts.suffix):iOpts.suffixEscaped||"}}";this.formatSeparator=iOpts.formatSeparator?iOpts.formatSeparator:iOpts.formatSeparator||",";this.unescapePrefix=iOpts.unescapeSuffix?"":iOpts.unescapePrefix||"-";this.unescapeSuffix=this.unescapePrefix?"":iOpts.unescapeSuffix||"";this.nestingPrefix=iOpts.nestingPrefix?regexEscape(iOpts.nestingPrefix):iOpts.nestingPrefixEscaped||regexEscape("$t(");this.nestingSuffix=iOpts.nestingSuffix?regexEscape(iOpts.nestingSuffix):iOpts.nestingSuffixEscaped||regexEscape(")");this.nestingOptionsSeparator=iOpts.nestingOptionsSeparator?iOpts.nestingOptionsSeparator:iOpts.nestingOptionsSeparator||",";this.maxReplaces=iOpts.maxReplaces?iOpts.maxReplaces:1e3;this.alwaysFormat=iOpts.alwaysFormat!==undefined?iOpts.alwaysFormat:false;this.resetRegExp()}},{key:"reset",value:function reset(){if(this.options)this.init(this.options)}},{key:"resetRegExp",value:function resetRegExp(){var regexpStr="".concat(this.prefix,"(.+?)").concat(this.suffix);this.regexp=new RegExp(regexpStr,"g");var regexpUnescapeStr="".concat(this.prefix).concat(this.unescapePrefix,"(.+?)").concat(this.unescapeSuffix).concat(this.suffix);this.regexpUnescape=new RegExp(regexpUnescapeStr,"g");var nestingRegexpStr="".concat(this.nestingPrefix,"(.+?)").concat(this.nestingSuffix);this.nestingRegexp=new RegExp(nestingRegexpStr,"g")}},{key:"interpolate",value:function interpolate(str,data,lng,options){var _this=this;var match;var value;var replaces;var defaultData=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{};function regexSafe(val){return val.replace(/\$/g,"$$$$")}var handleFormat=function handleFormat(key){if(key.indexOf(_this.formatSeparator)<0){var path=getPathWithDefaults(data,defaultData,key);return _this.alwaysFormat?_this.format(path,undefined,lng,_objectSpread$3(_objectSpread$3(_objectSpread$3({},options),data),{},{interpolationkey:key})):path}var p=key.split(_this.formatSeparator);var k=p.shift().trim();var f=p.join(_this.formatSeparator).trim();return _this.format(getPathWithDefaults(data,defaultData,k),f,lng,_objectSpread$3(_objectSpread$3(_objectSpread$3({},options),data),{},{interpolationkey:k}))};this.resetRegExp();var missingInterpolationHandler=options&&options.missingInterpolationHandler||this.options.missingInterpolationHandler;var skipOnVariables=options&&options.interpolation&&options.interpolation.skipOnVariables!==undefined?options.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;var todos=[{regex:this.regexpUnescape,safeValue:function safeValue(val){return regexSafe(val)}},{regex:this.regexp,safeValue:function safeValue(val){return _this.escapeValue?regexSafe(_this.escape(val)):regexSafe(val)}}];todos.forEach((function(todo){replaces=0;while(match=todo.regex.exec(str)){var matchedVar=match[1].trim();value=handleFormat(matchedVar);if(value===undefined){if(typeof missingInterpolationHandler==="function"){var temp=missingInterpolationHandler(str,match,options);value=typeof temp==="string"?temp:""}else if(options&&options.hasOwnProperty(matchedVar)){value=""}else if(skipOnVariables){value=match[0];continue}else{_this.logger.warn("missed to pass in variable ".concat(matchedVar," for interpolating ").concat(str));value=""}}else if(typeof value!=="string"&&!_this.useRawValueToEscape){value=makeString(value)}var safeValue=todo.safeValue(value);str=str.replace(match[0],safeValue);if(skipOnVariables){todo.regex.lastIndex+=safeValue.length;todo.regex.lastIndex-=match[0].length}else{todo.regex.lastIndex=0}replaces++;if(replaces>=_this.maxReplaces){break}}}));return str}},{key:"nest",value:function nest(str,fc){var _this2=this;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var match;var value;var clonedOptions=_objectSpread$3({},options);clonedOptions.applyPostProcessor=false;delete clonedOptions.defaultValue;function handleHasOptions(key,inheritedOptions){var sep=this.nestingOptionsSeparator;if(key.indexOf(sep)<0)return key;var c=key.split(new RegExp("".concat(sep,"[ ]*{")));var optionsString="{".concat(c[1]);key=c[0];optionsString=this.interpolate(optionsString,clonedOptions);optionsString=optionsString.replace(/'/g,'"');try{clonedOptions=JSON.parse(optionsString);if(inheritedOptions)clonedOptions=_objectSpread$3(_objectSpread$3({},inheritedOptions),clonedOptions)}catch(e){this.logger.warn("failed parsing options string in nesting for key ".concat(key),e);return"".concat(key).concat(sep).concat(optionsString)}delete clonedOptions.defaultValue;return key}while(match=this.nestingRegexp.exec(str)){var formatters=[];var doReduce=false;if(match[0].indexOf(this.formatSeparator)!==-1&&!/{.*}/.test(match[1])){var r=match[1].split(this.formatSeparator).map((function(elem){return elem.trim()}));match[1]=r.shift();formatters=r;doReduce=true}value=fc(handleHasOptions.call(this,match[1].trim(),clonedOptions),clonedOptions);if(value&&match[0]===str&&typeof value!=="string")return value;if(typeof value!=="string")value=makeString(value);if(!value){this.logger.warn("missed to resolve ".concat(match[1]," for nesting ").concat(str));value=""}if(doReduce){value=formatters.reduce((function(v,f){return _this2.format(v,f,options.lng,_objectSpread$3(_objectSpread$3({},options),{},{interpolationkey:match[1].trim()}))}),value.trim())}str=str.replace(match[0],value);this.regexp.lastIndex=0}return str}}]);return Interpolator}();function ownKeys$4(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread$4(target){for(var i=1;i-1){var p=formatStr.split("(");formatName=p[0].toLowerCase().trim();var optStr=p[1].substring(0,p[1].length-1);if(formatName==="currency"&&optStr.indexOf(":")<0){if(!formatOptions.currency)formatOptions.currency=optStr.trim()}else if(formatName==="relativetime"&&optStr.indexOf(":")<0){if(!formatOptions.range)formatOptions.range=optStr.trim()}else{var opts=optStr.split(";");opts.forEach((function(opt){if(!opt)return;var _opt$split=opt.split(":"),_opt$split2=_toArray__default["default"](_opt$split),key=_opt$split2[0],rest=_opt$split2.slice(1);var val=rest.join(":");if(val.trim()==="false")formatOptions[key.trim()]=false;if(val.trim()==="true")formatOptions[key.trim()]=true;if(!isNaN(val.trim()))formatOptions[key.trim()]=parseInt(val.trim(),10);if(!formatOptions[key.trim()])formatOptions[key.trim()]=val.trim()}))}}return{formatName:formatName,formatOptions:formatOptions}}var Formatter=function(){function Formatter(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};_classCallCheck__default["default"](this,Formatter);this.logger=baseLogger.create("formatter");this.options=options;this.formats={number:function number(val,lng,options){return new Intl.NumberFormat(lng,options).format(val)},currency:function currency(val,lng,options){return new Intl.NumberFormat(lng,_objectSpread$4(_objectSpread$4({},options),{},{style:"currency"})).format(val)},datetime:function datetime(val,lng,options){return new Intl.DateTimeFormat(lng,_objectSpread$4({},options)).format(val)},relativetime:function relativetime(val,lng,options){return new Intl.RelativeTimeFormat(lng,_objectSpread$4({},options)).format(val,options.range||"day")},list:function list(val,lng,options){return new Intl.ListFormat(lng,_objectSpread$4({},options)).format(val)}};this.init(options)}_createClass__default["default"](Formatter,[{key:"init",value:function init(services){var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{interpolation:{}};var iOpts=options.interpolation;this.formatSeparator=iOpts.formatSeparator?iOpts.formatSeparator:iOpts.formatSeparator||","}},{key:"add",value:function add(name,fc){this.formats[name.toLowerCase().trim()]=fc}},{key:"format",value:function format(value,_format,lng,options){var _this=this;var formats=_format.split(this.formatSeparator);var result=formats.reduce((function(mem,f){var _parseFormatStr=parseFormatStr(f),formatName=_parseFormatStr.formatName,formatOptions=_parseFormatStr.formatOptions;if(_this.formats[formatName]){var formatted=mem;try{var valOptions=options&&options.formatParams&&options.formatParams[options.interpolationkey]||{};var l=valOptions.locale||valOptions.lng||options.locale||options.lng||lng;formatted=_this.formats[formatName](mem,l,_objectSpread$4(_objectSpread$4(_objectSpread$4({},formatOptions),options),valOptions))}catch(error){_this.logger.warn(error)}return formatted}else{_this.logger.warn("there was no format function for ".concat(formatName))}return mem}),value);return result}}]);return Formatter}();function ownKeys$5(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread$5(target){for(var i=1;i3&&arguments[3]!==undefined?arguments[3]:{};_classCallCheck__default["default"](this,Connector);_this=_super.call(this);if(isIE10){EventEmitter.call(_assertThisInitialized__default["default"](_this))}_this.backend=backend;_this.store=store;_this.services=services;_this.languageUtils=services.languageUtils;_this.options=options;_this.logger=baseLogger.create("backendConnector");_this.state={};_this.queue=[];if(_this.backend&&_this.backend.init){_this.backend.init(services,options.backend,options)}return _this}_createClass__default["default"](Connector,[{key:"queueLoad",value:function queueLoad(languages,namespaces,options,callback){var _this2=this;var toLoad=[];var pending=[];var toLoadLanguages=[];var toLoadNamespaces=[];languages.forEach((function(lng){var hasAllNamespaces=true;namespaces.forEach((function(ns){var name="".concat(lng,"|").concat(ns);if(!options.reload&&_this2.store.hasResourceBundle(lng,ns)){_this2.state[name]=2}else if(_this2.state[name]<0);else if(_this2.state[name]===1){if(pending.indexOf(name)<0)pending.push(name)}else{_this2.state[name]=1;hasAllNamespaces=false;if(pending.indexOf(name)<0)pending.push(name);if(toLoad.indexOf(name)<0)toLoad.push(name);if(toLoadNamespaces.indexOf(ns)<0)toLoadNamespaces.push(ns)}}));if(!hasAllNamespaces)toLoadLanguages.push(lng)}));if(toLoad.length||pending.length){this.queue.push({pending:pending,loaded:{},errors:[],callback:callback})}return{toLoad:toLoad,pending:pending,toLoadLanguages:toLoadLanguages,toLoadNamespaces:toLoadNamespaces}}},{key:"loaded",value:function loaded(name,err,data){var s=name.split("|");var lng=s[0];var ns=s[1];if(err)this.emit("failedLoading",lng,ns,err);if(data){this.store.addResourceBundle(lng,ns,data)}this.state[name]=err?-1:2;var loaded={};this.queue.forEach((function(q){pushPath(q.loaded,[lng],ns);remove(q.pending,name);if(err)q.errors.push(err);if(q.pending.length===0&&!q.done){Object.keys(q.loaded).forEach((function(l){if(!loaded[l])loaded[l]=[];if(q.loaded[l].length){q.loaded[l].forEach((function(ns){if(loaded[l].indexOf(ns)<0)loaded[l].push(ns)}))}}));q.done=true;if(q.errors.length){q.callback(q.errors)}else{q.callback()}}}));this.emit("loaded",loaded);this.queue=this.queue.filter((function(q){return!q.done}))}},{key:"read",value:function read(lng,ns,fcName){var _this3=this;var tried=arguments.length>3&&arguments[3]!==undefined?arguments[3]:0;var wait=arguments.length>4&&arguments[4]!==undefined?arguments[4]:350;var callback=arguments.length>5?arguments[5]:undefined;if(!lng.length)return callback(null,{});return this.backend[fcName](lng,ns,(function(err,data){if(err&&data&&tried<5){setTimeout((function(){_this3.read.call(_this3,lng,ns,fcName,tried+1,wait*2,callback)}),wait);return}callback(err,data)}))}},{key:"prepareLoading",value:function prepareLoading(languages,namespaces){var _this4=this;var options=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var callback=arguments.length>3?arguments[3]:undefined;if(!this.backend){this.logger.warn("No backend was added via i18next.use. Will not load resources.");return callback&&callback()}if(typeof languages==="string")languages=this.languageUtils.toResolveHierarchy(languages);if(typeof namespaces==="string")namespaces=[namespaces];var toLoad=this.queueLoad(languages,namespaces,options,callback);if(!toLoad.toLoad.length){if(!toLoad.pending.length)callback();return null}toLoad.toLoad.forEach((function(name){_this4.loadOne(name)}))}},{key:"load",value:function load(languages,namespaces,callback){this.prepareLoading(languages,namespaces,{},callback)}},{key:"reload",value:function reload(languages,namespaces,callback){this.prepareLoading(languages,namespaces,{reload:true},callback)}},{key:"loadOne",value:function loadOne(name){var _this5=this;var prefix=arguments.length>1&&arguments[1]!==undefined?arguments[1]:"";var s=name.split("|");var lng=s[0];var ns=s[1];this.read(lng,ns,"read",undefined,undefined,(function(err,data){if(err)_this5.logger.warn("".concat(prefix,"loading namespace ").concat(ns," for language ").concat(lng," failed"),err);if(!err&&data)_this5.logger.log("".concat(prefix,"loaded namespace ").concat(ns," for language ").concat(lng),data);_this5.loaded(name,err,data)}))}},{key:"saveMissing",value:function saveMissing(languages,namespace,key,fallbackValue,isUpdate){var options=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{};if(this.services.utils&&this.services.utils.hasLoadedNamespace&&!this.services.utils.hasLoadedNamespace(namespace)){this.logger.warn('did not save key "'.concat(key,'" as the namespace "').concat(namespace,'" was not yet loaded'),"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");return}if(key===undefined||key===null||key==="")return;if(this.backend&&this.backend.create){this.backend.create(languages,namespace,key,fallbackValue,null,_objectSpread$5(_objectSpread$5({},options),{},{isUpdate:isUpdate}))}if(!languages||!languages[0])return;this.store.addResource(languages[0],namespace,key,fallbackValue)}}]);return Connector}(EventEmitter);function get(){return{debug:false,initImmediate:true,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:false,supportedLngs:false,nonExplicitSupportedLngs:false,load:"all",preload:false,simplifyPluralSuffix:true,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:false,saveMissing:false,updateMissing:false,saveMissingTo:"fallback",saveMissingPlurals:true,missingKeyHandler:false,missingInterpolationHandler:false,postProcess:false,postProcessPassResolved:false,returnNull:true,returnEmptyString:true,returnObjects:false,joinArrays:false,returnedObjectHandler:false,parseMissingKeyHandler:false,appendNamespaceToMissingKey:false,appendNamespaceToCIMode:false,overloadTranslationOptionHandler:function handle(args){var ret={};if(_typeof__default["default"](args[1])==="object")ret=args[1];if(typeof args[1]==="string")ret.defaultValue=args[1];if(typeof args[2]==="string")ret.tDescription=args[2];if(_typeof__default["default"](args[2])==="object"||_typeof__default["default"](args[3])==="object"){var options=args[3]||args[2];Object.keys(options).forEach((function(key){ret[key]=options[key]}))}return ret},interpolation:{escapeValue:true,format:function format(value,_format,lng,options){return value},prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:true}}}function transformOptions(options){if(typeof options.ns==="string")options.ns=[options.ns];if(typeof options.fallbackLng==="string")options.fallbackLng=[options.fallbackLng];if(typeof options.fallbackNS==="string")options.fallbackNS=[options.fallbackNS];if(options.supportedLngs&&options.supportedLngs.indexOf("cimode")<0){options.supportedLngs=options.supportedLngs.concat(["cimode"])}return options}function ownKeys$6(object,enumerableOnly){var keys=Object.keys(object);if(Object.getOwnPropertySymbols){var symbols=Object.getOwnPropertySymbols(object);if(enumerableOnly){symbols=symbols.filter((function(sym){return Object.getOwnPropertyDescriptor(object,sym).enumerable}))}keys.push.apply(keys,symbols)}return keys}function _objectSpread$6(target){for(var i=1;i0&&arguments[0]!==undefined?arguments[0]:{};var callback=arguments.length>1?arguments[1]:undefined;_classCallCheck__default["default"](this,I18n);_this=_super.call(this);if(isIE10){EventEmitter.call(_assertThisInitialized__default["default"](_this))}_this.options=transformOptions(options);_this.services={};_this.logger=baseLogger;_this.modules={external:[]};bindMemberFunctions(_assertThisInitialized__default["default"](_this));if(callback&&!_this.isInitialized&&!options.isClone){if(!_this.options.initImmediate){_this.init(options,callback);return _possibleConstructorReturn__default["default"](_this,_assertThisInitialized__default["default"](_this))}setTimeout((function(){_this.init(options,callback)}),0)}return _this}_createClass__default["default"](I18n,[{key:"init",value:function init(){var _this2=this;var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var callback=arguments.length>1?arguments[1]:undefined;if(typeof options==="function"){callback=options;options={}}if(!options.defaultNS&&options.ns){if(typeof options.ns==="string"){options.defaultNS=options.ns}else if(options.ns.indexOf("translation")<0){options.defaultNS=options.ns[0]}}var defOpts=get();this.options=_objectSpread$6(_objectSpread$6(_objectSpread$6({},defOpts),this.options),transformOptions(options));if(this.options.compatibilityAPI!=="v1"){this.options.interpolation=_objectSpread$6(_objectSpread$6({},defOpts.interpolation),this.options.interpolation)}if(options.keySeparator!==undefined){this.options.userDefinedKeySeparator=options.keySeparator}if(options.nsSeparator!==undefined){this.options.userDefinedNsSeparator=options.nsSeparator}function createClassOnDemand(ClassOrObject){if(!ClassOrObject)return null;if(typeof ClassOrObject==="function")return new ClassOrObject;return ClassOrObject}if(!this.options.isClone){if(this.modules.logger){baseLogger.init(createClassOnDemand(this.modules.logger),this.options)}else{baseLogger.init(null,this.options)}var formatter;if(this.modules.formatter){formatter=this.modules.formatter}else if(typeof Intl!=="undefined"){formatter=Formatter}var lu=new LanguageUtil(this.options);this.store=new ResourceStore(this.options.resources,this.options);var s=this.services;s.logger=baseLogger;s.resourceStore=this.store;s.languageUtils=lu;s.pluralResolver=new PluralResolver(lu,{prepend:this.options.pluralSeparator,compatibilityJSON:this.options.compatibilityJSON,simplifyPluralSuffix:this.options.simplifyPluralSuffix});if(formatter&&(!this.options.interpolation.format||this.options.interpolation.format===defOpts.interpolation.format)){s.formatter=createClassOnDemand(formatter);s.formatter.init(s,this.options);this.options.interpolation.format=s.formatter.format.bind(s.formatter)}s.interpolator=new Interpolator(this.options);s.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)};s.backendConnector=new Connector(createClassOnDemand(this.modules.backend),s.resourceStore,s,this.options);s.backendConnector.on("*",(function(event){for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key]}_this2.emit.apply(_this2,[event].concat(args))}));if(this.modules.languageDetector){s.languageDetector=createClassOnDemand(this.modules.languageDetector);s.languageDetector.init(s,this.options.detection,this.options)}if(this.modules.i18nFormat){s.i18nFormat=createClassOnDemand(this.modules.i18nFormat);if(s.i18nFormat.init)s.i18nFormat.init(this)}this.translator=new Translator(this.services,this.options);this.translator.on("*",(function(event){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2]}_this2.emit.apply(_this2,[event].concat(args))}));this.modules.external.forEach((function(m){if(m.init)m.init(_this2)}))}this.format=this.options.interpolation.format;if(!callback)callback=noop;if(this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){var codes=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);if(codes.length>0&&codes[0]!=="dev")this.options.lng=codes[0]}if(!this.services.languageDetector&&!this.options.lng){this.logger.warn("init: no languageDetector is used and no lng is defined")}var storeApi=["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"];storeApi.forEach((function(fcName){_this2[fcName]=function(){var _this2$store;return(_this2$store=_this2.store)[fcName].apply(_this2$store,arguments)}}));var storeApiChained=["addResource","addResources","addResourceBundle","removeResourceBundle"];storeApiChained.forEach((function(fcName){_this2[fcName]=function(){var _this2$store2;(_this2$store2=_this2.store)[fcName].apply(_this2$store2,arguments);return _this2}}));var deferred=defer();var load=function load(){var finish=function finish(err,t){if(_this2.isInitialized&&!_this2.initializedStoreOnce)_this2.logger.warn("init: i18next is already initialized. You should call init just once!");_this2.isInitialized=true;if(!_this2.options.isClone)_this2.logger.log("initialized",_this2.options);_this2.emit("initialized",_this2.options);deferred.resolve(t);callback(err,t)};if(_this2.languages&&_this2.options.compatibilityAPI!=="v1"&&!_this2.isInitialized)return finish(null,_this2.t.bind(_this2));_this2.changeLanguage(_this2.options.lng,finish)};if(this.options.resources||!this.options.initImmediate){load()}else{setTimeout(load,0)}return deferred}},{key:"loadResources",value:function loadResources(language){var _this3=this;var callback=arguments.length>1&&arguments[1]!==undefined?arguments[1]:noop;var usedCallback=callback;var usedLng=typeof language==="string"?language:this.language;if(typeof language==="function")usedCallback=language;if(!this.options.resources||this.options.partialBundledLanguages){if(usedLng&&usedLng.toLowerCase()==="cimode")return usedCallback();var toLoad=[];var append=function append(lng){if(!lng)return;var lngs=_this3.services.languageUtils.toResolveHierarchy(lng);lngs.forEach((function(l){if(toLoad.indexOf(l)<0)toLoad.push(l)}))};if(!usedLng){var fallbacks=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);fallbacks.forEach((function(l){return append(l)}))}else{append(usedLng)}if(this.options.preload){this.options.preload.forEach((function(l){return append(l)}))}this.services.backendConnector.load(toLoad,this.options.ns,(function(e){if(!e&&!_this3.resolvedLanguage&&_this3.language)_this3.setResolvedLanguage(_this3.language);usedCallback(e)}))}else{usedCallback(null)}}},{key:"reloadResources",value:function reloadResources(lngs,ns,callback){var deferred=defer();if(!lngs)lngs=this.languages;if(!ns)ns=this.options.ns;if(!callback)callback=noop;this.services.backendConnector.reload(lngs,ns,(function(err){deferred.resolve();callback(err)}));return deferred}},{key:"use",value:function use(module){if(!module)throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!module.type)throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");if(module.type==="backend"){this.modules.backend=module}if(module.type==="logger"||module.log&&module.warn&&module.error){this.modules.logger=module}if(module.type==="languageDetector"){this.modules.languageDetector=module}if(module.type==="i18nFormat"){this.modules.i18nFormat=module}if(module.type==="postProcessor"){postProcessor.addPostProcessor(module)}if(module.type==="formatter"){this.modules.formatter=module}if(module.type==="3rdParty"){this.modules.external.push(module)}return this}},{key:"setResolvedLanguage",value:function setResolvedLanguage(l){if(!l||!this.languages)return;if(["cimode","dev"].indexOf(l)>-1)return;for(var li=0;li-1)continue;if(this.store.hasLanguageSomeTranslations(lngInLngs)){this.resolvedLanguage=lngInLngs;break}}}},{key:"changeLanguage",value:function changeLanguage(lng,callback){var _this4=this;this.isLanguageChangingTo=lng;var deferred=defer();this.emit("languageChanging",lng);var setLngProps=function setLngProps(l){_this4.language=l;_this4.languages=_this4.services.languageUtils.toResolveHierarchy(l);_this4.resolvedLanguage=undefined;_this4.setResolvedLanguage(l)};var done=function done(err,l){if(l){setLngProps(l);_this4.translator.changeLanguage(l);_this4.isLanguageChangingTo=undefined;_this4.emit("languageChanged",l);_this4.logger.log("languageChanged",l)}else{_this4.isLanguageChangingTo=undefined}deferred.resolve((function(){return _this4.t.apply(_this4,arguments)}));if(callback)callback(err,(function(){return _this4.t.apply(_this4,arguments)}))};var setLng=function setLng(lngs){if(!lng&&!lngs&&_this4.services.languageDetector)lngs=[];var l=typeof lngs==="string"?lngs:_this4.services.languageUtils.getBestMatchFromCodes(lngs);if(l){if(!_this4.language){setLngProps(l)}if(!_this4.translator.language)_this4.translator.changeLanguage(l);if(_this4.services.languageDetector)_this4.services.languageDetector.cacheUserLanguage(l)}_this4.loadResources(l,(function(err){done(err,l)}))};if(!lng&&this.services.languageDetector&&!this.services.languageDetector.async){setLng(this.services.languageDetector.detect())}else if(!lng&&this.services.languageDetector&&this.services.languageDetector.async){this.services.languageDetector.detect(setLng)}else{setLng(lng)}return deferred}},{key:"getFixedT",value:function getFixedT(lng,ns,keyPrefix){var _this5=this;var fixedT=function fixedT(key,opts){var options;if(_typeof__default["default"](opts)!=="object"){for(var _len3=arguments.length,rest=new Array(_len3>2?_len3-2:0),_key3=2;_key3<_len3;_key3++){rest[_key3-2]=arguments[_key3]}options=_this5.options.overloadTranslationOptionHandler([key,opts].concat(rest))}else{options=_objectSpread$6({},opts)}options.lng=options.lng||fixedT.lng;options.lngs=options.lngs||fixedT.lngs;options.ns=options.ns||fixedT.ns;var keySeparator=_this5.options.keySeparator||".";var resultKey=keyPrefix?"".concat(keyPrefix).concat(keySeparator).concat(key):key;return _this5.t(resultKey,options)};if(typeof lng==="string"){fixedT.lng=lng}else{fixedT.lngs=lng}fixedT.ns=ns;fixedT.keyPrefix=keyPrefix;return fixedT}},{key:"t",value:function t(){var _this$translator;return this.translator&&(_this$translator=this.translator).translate.apply(_this$translator,arguments)}},{key:"exists",value:function exists(){var _this$translator2;return this.translator&&(_this$translator2=this.translator).exists.apply(_this$translator2,arguments)}},{key:"setDefaultNamespace",value:function setDefaultNamespace(ns){this.options.defaultNS=ns}},{key:"hasLoadedNamespace",value:function hasLoadedNamespace(ns){var _this6=this;var options=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};if(!this.isInitialized){this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages);return false}if(!this.languages||!this.languages.length){this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages);return false}var lng=this.resolvedLanguage||this.languages[0];var fallbackLng=this.options?this.options.fallbackLng:false;var lastLng=this.languages[this.languages.length-1];if(lng.toLowerCase()==="cimode")return true;var loadNotPending=function loadNotPending(l,n){var loadState=_this6.services.backendConnector.state["".concat(l,"|").concat(n)];return loadState===-1||loadState===2};if(options.precheck){var preResult=options.precheck(this,loadNotPending);if(preResult!==undefined)return preResult}if(this.hasResourceBundle(lng,ns))return true;if(!this.services.backendConnector.backend)return true;if(loadNotPending(lng,ns)&&(!fallbackLng||loadNotPending(lastLng,ns)))return true;return false}},{key:"loadNamespaces",value:function loadNamespaces(ns,callback){var _this7=this;var deferred=defer();if(!this.options.ns){callback&&callback();return Promise.resolve()}if(typeof ns==="string")ns=[ns];ns.forEach((function(n){if(_this7.options.ns.indexOf(n)<0)_this7.options.ns.push(n)}));this.loadResources((function(err){deferred.resolve();if(callback)callback(err)}));return deferred}},{key:"loadLanguages",value:function loadLanguages(lngs,callback){var deferred=defer();if(typeof lngs==="string")lngs=[lngs];var preloaded=this.options.preload||[];var newLngs=lngs.filter((function(lng){return preloaded.indexOf(lng)<0}));if(!newLngs.length){if(callback)callback();return Promise.resolve()}this.options.preload=preloaded.concat(newLngs);this.loadResources((function(err){deferred.resolve();if(callback)callback(err)}));return deferred}},{key:"dir",value:function dir(lng){if(!lng)lng=this.resolvedLanguage||(this.languages&&this.languages.length>0?this.languages[0]:this.language);if(!lng)return"rtl";var rtlLngs=["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"];return rtlLngs.indexOf(this.services.languageUtils.getLanguagePartFromCode(lng))>-1||lng.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}},{key:"cloneInstance",value:function cloneInstance(){var _this8=this;var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var callback=arguments.length>1&&arguments[1]!==undefined?arguments[1]:noop;var mergedOptions=_objectSpread$6(_objectSpread$6(_objectSpread$6({},this.options),options),{isClone:true});var clone=new I18n(mergedOptions);var membersToCopy=["store","services","language"];membersToCopy.forEach((function(m){clone[m]=_this8[m]}));clone.services=_objectSpread$6({},this.services);clone.services.utils={hasLoadedNamespace:clone.hasLoadedNamespace.bind(clone)};clone.translator=new Translator(clone.services,clone.options);clone.translator.on("*",(function(event){for(var _len4=arguments.length,args=new Array(_len4>1?_len4-1:0),_key4=1;_key4<_len4;_key4++){args[_key4-1]=arguments[_key4]}clone.emit.apply(clone,[event].concat(args))}));clone.init(mergedOptions,callback);clone.translator.options=clone.options;clone.translator.backendConnector.services.utils={hasLoadedNamespace:clone.hasLoadedNamespace.bind(clone)};return clone}},{key:"toJSON",value:function toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}]);return I18n}(EventEmitter);_defineProperty__default["default"](I18n,"createInstance",(function(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var callback=arguments.length>1?arguments[1]:undefined;return new I18n(options,callback)}));var instance=I18n.createInstance();instance.createInstance=I18n.createInstance;module.exports=instance},{"@babel/runtime/helpers/assertThisInitialized":4,"@babel/runtime/helpers/classCallCheck":5,"@babel/runtime/helpers/createClass":6,"@babel/runtime/helpers/defineProperty":7,"@babel/runtime/helpers/getPrototypeOf":8,"@babel/runtime/helpers/inherits":9,"@babel/runtime/helpers/possibleConstructorReturn":12,"@babel/runtime/helpers/toArray":14,"@babel/runtime/helpers/typeof":15}],114:[function(require,module,exports){ /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.pow(2,1-eBias)}if(value*c>=2){e++;c/=2}if(e+eBias>=eMax){m=0;e=eMax}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128}},{}],115:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}}else{module.exports=function inherits(ctor,superCtor){if(superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}}},{}],116:[function(require,module,exports){"use strict";function get_beautify(js_beautify,css_beautify,html_beautify){var beautify=function(src,config){return js_beautify.js_beautify(src,config)};beautify.js=js_beautify.js_beautify;beautify.css=css_beautify.css_beautify;beautify.html=html_beautify.html_beautify;beautify.js_beautify=js_beautify.js_beautify;beautify.css_beautify=css_beautify.css_beautify;beautify.html_beautify=html_beautify.html_beautify;return beautify}if(typeof define==="function"&&define.amd){define(["./lib/beautify","./lib/beautify-css","./lib/beautify-html"],(function(js_beautify,css_beautify,html_beautify){return get_beautify(js_beautify,css_beautify,html_beautify)}))}else{(function(mod){var beautifier=require("./src/index");beautifier.js_beautify=beautifier.js;beautifier.css_beautify=beautifier.css;beautifier.html_beautify=beautifier.html;mod.exports=get_beautify(beautifier,beautifier,beautifier)})(module)}},{"./src/index":134}],117:[function(require,module,exports){"use strict";function Directives(start_block_pattern,end_block_pattern){start_block_pattern=typeof start_block_pattern==="string"?start_block_pattern:start_block_pattern.source;end_block_pattern=typeof end_block_pattern==="string"?end_block_pattern:end_block_pattern.source;this.__directives_block_pattern=new RegExp(start_block_pattern+/ beautify( \w+[:]\w+)+ /.source+end_block_pattern,"g");this.__directive_pattern=/ (\w+)[:](\w+)/g;this.__directives_end_ignore_pattern=new RegExp(start_block_pattern+/\sbeautify\signore:end\s/.source+end_block_pattern,"g")}Directives.prototype.get_directives=function(text){if(!text.match(this.__directives_block_pattern)){return null}var directives={};this.__directive_pattern.lastIndex=0;var directive_match=this.__directive_pattern.exec(text);while(directive_match){directives[directive_match[1]]=directive_match[2];directive_match=this.__directive_pattern.exec(text)}return directives};Directives.prototype.readIgnored=function(input){return input.readUntilAfter(this.__directives_end_ignore_pattern)};module.exports.Directives=Directives},{}],118:[function(require,module,exports){"use strict";var regexp_has_sticky=RegExp.prototype.hasOwnProperty("sticky");function InputScanner(input_string){this.__input=input_string||"";this.__input_length=this.__input.length;this.__position=0}InputScanner.prototype.restart=function(){this.__position=0};InputScanner.prototype.back=function(){if(this.__position>0){this.__position-=1}};InputScanner.prototype.hasNext=function(){return this.__position=0&&index=0&&index=testVal.length&&this.__input.substring(start-testVal.length,start).toLowerCase()===testVal};module.exports.InputScanner=InputScanner},{}],119:[function(require,module,exports){"use strict";function Options(options,merge_child_field){this.raw_options=_mergeOpts(options,merge_child_field);this.disabled=this._get_boolean("disabled");this.eol=this._get_characters("eol","auto");this.end_with_newline=this._get_boolean("end_with_newline");this.indent_size=this._get_number("indent_size",4);this.indent_char=this._get_characters("indent_char"," ");this.indent_level=this._get_number("indent_level");this.preserve_newlines=this._get_boolean("preserve_newlines",true);this.max_preserve_newlines=this._get_number("max_preserve_newlines",32786);if(!this.preserve_newlines){this.max_preserve_newlines=0}this.indent_with_tabs=this._get_boolean("indent_with_tabs",this.indent_char==="\t");if(this.indent_with_tabs){this.indent_char="\t";if(this.indent_size===1){this.indent_size=4}}this.wrap_line_length=this._get_number("wrap_line_length",this._get_number("max_char"));this.indent_empty_lines=this._get_boolean("indent_empty_lines");this.templating=this._get_selection_list("templating",["auto","none","django","erb","handlebars","php","smarty"],["auto"])}Options.prototype._get_array=function(name,default_value){var option_value=this.raw_options[name];var result=default_value||[];if(typeof option_value==="object"){if(option_value!==null&&typeof option_value.concat==="function"){result=option_value.concat()}}else if(typeof option_value==="string"){result=option_value.split(/[^a-zA-Z0-9_\/\-]+/)}return result};Options.prototype._get_boolean=function(name,default_value){var option_value=this.raw_options[name];var result=option_value===undefined?!!default_value:!!option_value;return result};Options.prototype._get_characters=function(name,default_value){var option_value=this.raw_options[name];var result=default_value||"";if(typeof option_value==="string"){result=option_value.replace(/\\r/,"\r").replace(/\\n/,"\n").replace(/\\t/,"\t")}return result};Options.prototype._get_number=function(name,default_value){var option_value=this.raw_options[name];default_value=parseInt(default_value,10);if(isNaN(default_value)){default_value=0}var result=parseInt(option_value,10);if(isNaN(result)){result=default_value}return result};Options.prototype._get_selection=function(name,selection_list,default_value){var result=this._get_selection_list(name,selection_list,default_value);if(result.length!==1){throw new Error("Invalid Option Value: The option '"+name+"' can only be one of the following values:\n"+selection_list+"\nYou passed in: '"+this.raw_options[name]+"'")}return result[0]};Options.prototype._get_selection_list=function(name,selection_list,default_value){if(!selection_list||selection_list.length===0){throw new Error("Selection list cannot be empty.")}default_value=default_value||[selection_list[0]];if(!this._is_valid_selection(default_value,selection_list)){throw new Error("Invalid Default Value!")}var result=this._get_array(name,default_value);if(!this._is_valid_selection(result,selection_list)){throw new Error("Invalid Option Value: The option '"+name+"' can contain only the following values:\n"+selection_list+"\nYou passed in: '"+this.raw_options[name]+"'")}return result};Options.prototype._is_valid_selection=function(result,selection_list){return result.length&&selection_list.length&&!result.some((function(item){return selection_list.indexOf(item)===-1}))};function _mergeOpts(allOptions,childFieldName){var finalOpts={};allOptions=_normalizeOpts(allOptions);var name;for(name in allOptions){if(name!==childFieldName){finalOpts[name]=allOptions[name]}}if(childFieldName&&allOptions[childFieldName]){for(name in allOptions[childFieldName]){finalOpts[name]=allOptions[childFieldName][name]}}return finalOpts}function _normalizeOpts(options){var convertedOpts={};var key;for(key in options){var newKey=key.replace(/-/g,"_");convertedOpts[newKey]=options[key]}return convertedOpts}module.exports.Options=Options;module.exports.normalizeOpts=_normalizeOpts;module.exports.mergeOpts=_mergeOpts},{}],120:[function(require,module,exports){"use strict";function OutputLine(parent){this.__parent=parent;this.__character_count=0;this.__indent_count=-1;this.__alignment_count=0;this.__wrap_point_index=0;this.__wrap_point_character_count=0;this.__wrap_point_indent_count=-1;this.__wrap_point_alignment_count=0;this.__items=[]}OutputLine.prototype.clone_empty=function(){var line=new OutputLine(this.__parent);line.set_indent(this.__indent_count,this.__alignment_count);return line};OutputLine.prototype.item=function(index){if(index<0){return this.__items[this.__items.length+index]}else{return this.__items[index]}};OutputLine.prototype.has_match=function(pattern){for(var lastCheckedOutput=this.__items.length-1;lastCheckedOutput>=0;lastCheckedOutput--){if(this.__items[lastCheckedOutput].match(pattern)){return true}}return false};OutputLine.prototype.set_indent=function(indent,alignment){if(this.is_empty()){this.__indent_count=indent||0;this.__alignment_count=alignment||0;this.__character_count=this.__parent.get_indent_size(this.__indent_count,this.__alignment_count)}};OutputLine.prototype._set_wrap_point=function(){if(this.__parent.wrap_line_length){this.__wrap_point_index=this.__items.length;this.__wrap_point_character_count=this.__character_count;this.__wrap_point_indent_count=this.__parent.next_line.__indent_count;this.__wrap_point_alignment_count=this.__parent.next_line.__alignment_count}};OutputLine.prototype._should_wrap=function(){return this.__wrap_point_index&&this.__character_count>this.__parent.wrap_line_length&&this.__wrap_point_character_count>this.__parent.next_line.__character_count};OutputLine.prototype._allow_wrap=function(){if(this._should_wrap()){this.__parent.add_new_line();var next=this.__parent.current_line;next.set_indent(this.__wrap_point_indent_count,this.__wrap_point_alignment_count);next.__items=this.__items.slice(this.__wrap_point_index);this.__items=this.__items.slice(0,this.__wrap_point_index);next.__character_count+=this.__character_count-this.__wrap_point_character_count;this.__character_count=this.__wrap_point_character_count;if(next.__items[0]===" "){next.__items.splice(0,1);next.__character_count-=1}return true}return false};OutputLine.prototype.is_empty=function(){return this.__items.length===0};OutputLine.prototype.last=function(){if(!this.is_empty()){return this.__items[this.__items.length-1]}else{return null}};OutputLine.prototype.push=function(item){this.__items.push(item);var last_newline_index=item.lastIndexOf("\n");if(last_newline_index!==-1){this.__character_count=item.length-last_newline_index}else{this.__character_count+=item.length}};OutputLine.prototype.pop=function(){var item=null;if(!this.is_empty()){item=this.__items.pop();this.__character_count-=item.length}return item};OutputLine.prototype._remove_indent=function(){if(this.__indent_count>0){this.__indent_count-=1;this.__character_count-=this.__parent.indent_size}};OutputLine.prototype._remove_wrap_indent=function(){if(this.__wrap_point_indent_count>0){this.__wrap_point_indent_count-=1}};OutputLine.prototype.trim=function(){while(this.last()===" "){this.__items.pop();this.__character_count-=1}};OutputLine.prototype.toString=function(){var result="";if(this.is_empty()){if(this.__parent.indent_empty_lines){result=this.__parent.get_indent_string(this.__indent_count)}}else{result=this.__parent.get_indent_string(this.__indent_count,this.__alignment_count);result+=this.__items.join("")}return result};function IndentStringCache(options,baseIndentString){this.__cache=[""];this.__indent_size=options.indent_size;this.__indent_string=options.indent_char;if(!options.indent_with_tabs){this.__indent_string=new Array(options.indent_size+1).join(options.indent_char)}baseIndentString=baseIndentString||"";if(options.indent_level>0){baseIndentString=new Array(options.indent_level+1).join(this.__indent_string)}this.__base_string=baseIndentString;this.__base_string_length=baseIndentString.length}IndentStringCache.prototype.get_indent_size=function(indent,column){var result=this.__base_string_length;column=column||0;if(indent<0){result=0}result+=indent*this.__indent_size;result+=column;return result};IndentStringCache.prototype.get_indent_string=function(indent_level,column){var result=this.__base_string;column=column||0;if(indent_level<0){indent_level=0;result=""}column+=indent_level*this.__indent_size;this.__ensure_cache(column);result+=this.__cache[column];return result};IndentStringCache.prototype.__ensure_cache=function(column){while(column>=this.__cache.length){this.__add_column()}};IndentStringCache.prototype.__add_column=function(){var column=this.__cache.length;var indent=0;var result="";if(this.__indent_size&&column>=this.__indent_size){indent=Math.floor(column/this.__indent_size);column-=indent*this.__indent_size;result=new Array(indent+1).join(this.__indent_string)}if(column){result+=new Array(column+1).join(" ")}this.__cache.push(result)};function Output(options,baseIndentString){this.__indent_cache=new IndentStringCache(options,baseIndentString);this.raw=false;this._end_with_newline=options.end_with_newline;this.indent_size=options.indent_size;this.wrap_line_length=options.wrap_line_length;this.indent_empty_lines=options.indent_empty_lines;this.__lines=[];this.previous_line=null;this.current_line=null;this.next_line=new OutputLine(this);this.space_before_token=false;this.non_breaking_space=false;this.previous_token_wrapped=false;this.__add_outputline()}Output.prototype.__add_outputline=function(){this.previous_line=this.current_line;this.current_line=this.next_line.clone_empty();this.__lines.push(this.current_line)};Output.prototype.get_line_number=function(){return this.__lines.length};Output.prototype.get_indent_string=function(indent,column){return this.__indent_cache.get_indent_string(indent,column)};Output.prototype.get_indent_size=function(indent,column){return this.__indent_cache.get_indent_size(indent,column)};Output.prototype.is_empty=function(){return!this.previous_line&&this.current_line.is_empty()};Output.prototype.add_new_line=function(force_newline){if(this.is_empty()||!force_newline&&this.just_added_newline()){return false}if(!this.raw){this.__add_outputline()}return true};Output.prototype.get_code=function(eol){this.trim(true);var last_item=this.current_line.pop();if(last_item){if(last_item[last_item.length-1]==="\n"){last_item=last_item.replace(/\n+$/g,"")}this.current_line.push(last_item)}if(this._end_with_newline){this.__add_outputline()}var sweet_code=this.__lines.join("\n");if(eol!=="\n"){sweet_code=sweet_code.replace(/[\n]/g,eol)}return sweet_code};Output.prototype.set_wrap_point=function(){this.current_line._set_wrap_point()};Output.prototype.set_indent=function(indent,alignment){indent=indent||0;alignment=alignment||0;this.next_line.set_indent(indent,alignment);if(this.__lines.length>1){this.current_line.set_indent(indent,alignment);return true}this.current_line.set_indent();return false};Output.prototype.add_raw_token=function(token){for(var x=0;x1&&this.current_line.is_empty()){this.__lines.pop();this.current_line=this.__lines[this.__lines.length-1];this.current_line.trim()}this.previous_line=this.__lines.length>1?this.__lines[this.__lines.length-2]:null};Output.prototype.just_added_newline=function(){return this.current_line.is_empty()};Output.prototype.just_added_blankline=function(){return this.is_empty()||this.current_line.is_empty()&&this.previous_line.is_empty()};Output.prototype.ensure_empty_line_above=function(starts_with,ends_with){var index=this.__lines.length-2;while(index>=0){var potentialEmptyLine=this.__lines[index];if(potentialEmptyLine.is_empty()){break}else if(potentialEmptyLine.item(0).indexOf(starts_with)!==0&&potentialEmptyLine.item(-1)!==ends_with){this.__lines.splice(index+1,0,new OutputLine(this));this.previous_line=this.__lines[this.__lines.length-2];break}index--}};module.exports.Output=Output},{}],121:[function(require,module,exports){"use strict";function Pattern(input_scanner,parent){this._input=input_scanner;this._starting_pattern=null;this._match_pattern=null;this._until_pattern=null;this._until_after=false;if(parent){this._starting_pattern=this._input.get_regexp(parent._starting_pattern,true);this._match_pattern=this._input.get_regexp(parent._match_pattern,true);this._until_pattern=this._input.get_regexp(parent._until_pattern);this._until_after=parent._until_after}}Pattern.prototype.read=function(){var result=this._input.read(this._starting_pattern);if(!this._starting_pattern||result){result+=this._input.read(this._match_pattern,this._until_pattern,this._until_after)}return result};Pattern.prototype.read_match=function(){return this._input.match(this._match_pattern)};Pattern.prototype.until_after=function(pattern){var result=this._create();result._until_after=true;result._until_pattern=this._input.get_regexp(pattern);result._update();return result};Pattern.prototype.until=function(pattern){var result=this._create();result._until_after=false;result._until_pattern=this._input.get_regexp(pattern);result._update();return result};Pattern.prototype.starting_with=function(pattern){var result=this._create();result._starting_pattern=this._input.get_regexp(pattern,true);result._update();return result};Pattern.prototype.matching=function(pattern){var result=this._create();result._match_pattern=this._input.get_regexp(pattern,true);result._update();return result};Pattern.prototype._create=function(){return new Pattern(this._input,this)};Pattern.prototype._update=function(){};module.exports.Pattern=Pattern},{}],122:[function(require,module,exports){"use strict";var Pattern=require("./pattern").Pattern;var template_names={django:false,erb:false,handlebars:false,php:false,smarty:false};function TemplatablePattern(input_scanner,parent){Pattern.call(this,input_scanner,parent);this.__template_pattern=null;this._disabled=Object.assign({},template_names);this._excluded=Object.assign({},template_names);if(parent){this.__template_pattern=this._input.get_regexp(parent.__template_pattern);this._excluded=Object.assign(this._excluded,parent._excluded);this._disabled=Object.assign(this._disabled,parent._disabled)}var pattern=new Pattern(input_scanner);this.__patterns={handlebars_comment:pattern.starting_with(/{{!--/).until_after(/--}}/),handlebars_unescaped:pattern.starting_with(/{{{/).until_after(/}}}/),handlebars:pattern.starting_with(/{{/).until_after(/}}/),php:pattern.starting_with(/<\?(?:[= ]|php)/).until_after(/\?>/),erb:pattern.starting_with(/<%[^%]/).until_after(/[^%]%>/),django:pattern.starting_with(/{%/).until_after(/%}/),django_value:pattern.starting_with(/{{/).until_after(/}}/),django_comment:pattern.starting_with(/{#/).until_after(/#}/),smarty:pattern.starting_with(/{(?=[^}{\s\n])/).until_after(/[^\s\n]}/),smarty_comment:pattern.starting_with(/{\*/).until_after(/\*}/),smarty_literal:pattern.starting_with(/{literal}/).until_after(/{\/literal}/)}}TemplatablePattern.prototype=new Pattern;TemplatablePattern.prototype._create=function(){return new TemplatablePattern(this._input,this)};TemplatablePattern.prototype._update=function(){this.__set_templated_pattern()};TemplatablePattern.prototype.disable=function(language){var result=this._create();result._disabled[language]=true;result._update();return result};TemplatablePattern.prototype.read_options=function(options){var result=this._create();for(var language in template_names){result._disabled[language]=options.templating.indexOf(language)===-1}result._update();return result};TemplatablePattern.prototype.exclude=function(language){var result=this._create();result._excluded[language]=true;result._update();return result};TemplatablePattern.prototype.read=function(){var result="";if(this._match_pattern){result=this._input.read(this._starting_pattern)}else{result=this._input.read(this._starting_pattern,this.__template_pattern)}var next=this._read_template();while(next){if(this._match_pattern){next+=this._input.read(this._match_pattern)}else{next+=this._input.readUntil(this.__template_pattern)}result+=next;next=this._read_template()}if(this._until_after){result+=this._input.readUntilAfter(this._until_pattern)}return result};TemplatablePattern.prototype.__set_templated_pattern=function(){var items=[];if(!this._disabled.php){items.push(this.__patterns.php._starting_pattern.source)}if(!this._disabled.handlebars){items.push(this.__patterns.handlebars._starting_pattern.source)}if(!this._disabled.erb){items.push(this.__patterns.erb._starting_pattern.source)}if(!this._disabled.django){items.push(this.__patterns.django._starting_pattern.source);items.push(this.__patterns.django_value._starting_pattern.source);items.push(this.__patterns.django_comment._starting_pattern.source)}if(!this._disabled.smarty){items.push(this.__patterns.smarty._starting_pattern.source)}if(this._until_pattern){items.push(this._until_pattern.source)}this.__template_pattern=this._input.get_regexp("(?:"+items.join("|")+")")};TemplatablePattern.prototype._read_template=function(){var resulting_string="";var c=this._input.peek();if(c==="<"){var peek1=this._input.peek(1);if(!this._disabled.php&&!this._excluded.php&&peek1==="?"){resulting_string=resulting_string||this.__patterns.php.read()}if(!this._disabled.erb&&!this._excluded.erb&&peek1==="%"){resulting_string=resulting_string||this.__patterns.erb.read()}}else if(c==="{"){if(!this._disabled.handlebars&&!this._excluded.handlebars){resulting_string=resulting_string||this.__patterns.handlebars_comment.read();resulting_string=resulting_string||this.__patterns.handlebars_unescaped.read();resulting_string=resulting_string||this.__patterns.handlebars.read()}if(!this._disabled.django){if(!this._excluded.django&&!this._excluded.handlebars){resulting_string=resulting_string||this.__patterns.django_value.read()}if(!this._excluded.django){resulting_string=resulting_string||this.__patterns.django_comment.read();resulting_string=resulting_string||this.__patterns.django.read()}}if(!this._disabled.smarty){if(this._disabled.django&&this._disabled.handlebars){resulting_string=resulting_string||this.__patterns.smarty_comment.read();resulting_string=resulting_string||this.__patterns.smarty_literal.read();resulting_string=resulting_string||this.__patterns.smarty.read()}}}return resulting_string};module.exports.TemplatablePattern=TemplatablePattern},{"./pattern":121}],123:[function(require,module,exports){"use strict";function Token(type,text,newlines,whitespace_before){this.type=type;this.text=text;this.comments_before=null;this.newlines=newlines||0;this.whitespace_before=whitespace_before||"";this.parent=null;this.next=null;this.previous=null;this.opened=null;this.closed=null;this.directives=null}module.exports.Token=Token},{}],124:[function(require,module,exports){"use strict";var InputScanner=require("../core/inputscanner").InputScanner;var Token=require("../core/token").Token;var TokenStream=require("../core/tokenstream").TokenStream;var WhitespacePattern=require("./whitespacepattern").WhitespacePattern;var TOKEN={START:"TK_START",RAW:"TK_RAW",EOF:"TK_EOF"};var Tokenizer=function(input_string,options){this._input=new InputScanner(input_string);this._options=options||{};this.__tokens=null;this._patterns={};this._patterns.whitespace=new WhitespacePattern(this._input)};Tokenizer.prototype.tokenize=function(){this._input.restart();this.__tokens=new TokenStream;this._reset();var current;var previous=new Token(TOKEN.START,"");var open_token=null;var open_stack=[];var comments=new TokenStream;while(previous.type!==TOKEN.EOF){current=this._get_next_token(previous,open_token);while(this._is_comment(current)){comments.add(current);current=this._get_next_token(previous,open_token)}if(!comments.isEmpty()){current.comments_before=comments;comments=new TokenStream}current.parent=open_token;if(this._is_opening(current)){open_stack.push(open_token);open_token=current}else if(open_token&&this._is_closing(current,open_token)){current.opened=open_token;open_token.closed=current;open_token=open_stack.pop();current.parent=open_token}current.previous=previous;previous.next=current;this.__tokens.add(current);previous=current}return this.__tokens};Tokenizer.prototype._is_first_token=function(){return this.__tokens.isEmpty()};Tokenizer.prototype._reset=function(){};Tokenizer.prototype._get_next_token=function(previous_token,open_token){this._readWhitespace();var resulting_string=this._input.read(/.+/g);if(resulting_string){return this._create_token(TOKEN.RAW,resulting_string)}else{return this._create_token(TOKEN.EOF,"")}};Tokenizer.prototype._is_comment=function(current_token){return false};Tokenizer.prototype._is_opening=function(current_token){return false};Tokenizer.prototype._is_closing=function(current_token,open_token){return false};Tokenizer.prototype._create_token=function(type,text){var token=new Token(type,text,this._patterns.whitespace.newline_count,this._patterns.whitespace.whitespace_before_token);return token};Tokenizer.prototype._readWhitespace=function(){return this._patterns.whitespace.read()};module.exports.Tokenizer=Tokenizer;module.exports.TOKEN=TOKEN},{"../core/inputscanner":118,"../core/token":123,"../core/tokenstream":125,"./whitespacepattern":126}],125:[function(require,module,exports){"use strict";function TokenStream(parent_token){this.__tokens=[];this.__tokens_length=this.__tokens.length;this.__position=0;this.__parent_token=parent_token}TokenStream.prototype.restart=function(){this.__position=0};TokenStream.prototype.isEmpty=function(){return this.__tokens_length===0};TokenStream.prototype.hasNext=function(){return this.__position=0&&index0){this._indentLevel--}};Beautifier.prototype.beautify=function(){if(this._options.disabled){return this._source_text}var source_text=this._source_text;var eol=this._options.eol;if(eol==="auto"){eol="\n";if(source_text&&lineBreak.test(source_text||"")){eol=source_text.match(lineBreak)[0]}}source_text=source_text.replace(allLineBreaks,"\n");var baseIndentString=source_text.match(/^[\t ]*/)[0];this._output=new Output(this._options,baseIndentString);this._input=new InputScanner(source_text);this._indentLevel=0;this._nestedLevel=0;this._ch=null;var parenLevel=0;var insideRule=false;var insidePropertyValue=false;var enteringConditionalGroup=false;var insideAtExtend=false;var insideAtImport=false;var topCharacter=this._ch;var whitespace;var isAfterSpace;var previous_ch;while(true){whitespace=this._input.read(whitespacePattern);isAfterSpace=whitespace!=="";previous_ch=topCharacter;this._ch=this._input.next();if(this._ch==="\\"&&this._input.hasNext()){this._ch+=this._input.next()}topCharacter=this._ch;if(!this._ch){break}else if(this._ch==="/"&&this._input.peek()==="*"){this._output.add_new_line();this._input.back();var comment=this._input.read(block_comment_pattern);var directives=directives_core.get_directives(comment);if(directives&&directives.ignore==="start"){comment+=directives_core.readIgnored(this._input)}this.print_string(comment);this.eatWhitespace(true);this._output.add_new_line()}else if(this._ch==="/"&&this._input.peek()==="/"){this._output.space_before_token=true;this._input.back();this.print_string(this._input.read(comment_pattern));this.eatWhitespace(true)}else if(this._ch==="@"){this.preserveSingleSpace(isAfterSpace);if(this._input.peek()==="{"){this.print_string(this._ch+this.eatString("}"))}else{this.print_string(this._ch);var variableOrRule=this._input.peekUntilAfter(/[: ,;{}()[\]\/='"]/g);if(variableOrRule.match(/[ :]$/)){variableOrRule=this.eatString(": ").replace(/\s$/,"");this.print_string(variableOrRule);this._output.space_before_token=true}variableOrRule=variableOrRule.replace(/\s$/,"");if(variableOrRule==="extend"){insideAtExtend=true}else if(variableOrRule==="import"){insideAtImport=true}if(variableOrRule in this.NESTED_AT_RULE){this._nestedLevel+=1;if(variableOrRule in this.CONDITIONAL_GROUP_RULE){enteringConditionalGroup=true}}else if(!insideRule&&parenLevel===0&&variableOrRule.indexOf(":")!==-1){insidePropertyValue=true;this.indent()}}}else if(this._ch==="#"&&this._input.peek()==="{"){this.preserveSingleSpace(isAfterSpace);this.print_string(this._ch+this.eatString("}"))}else if(this._ch==="{"){if(insidePropertyValue){insidePropertyValue=false;this.outdent()}if(enteringConditionalGroup){enteringConditionalGroup=false;insideRule=this._indentLevel>=this._nestedLevel}else{insideRule=this._indentLevel>=this._nestedLevel-1}if(this._options.newline_between_rules&&insideRule){if(this._output.previous_line&&this._output.previous_line.item(-1)!=="{"){this._output.ensure_empty_line_above("/",",")}}this._output.space_before_token=true;if(this._options.brace_style==="expand"){this._output.add_new_line();this.print_string(this._ch);this.indent();this._output.set_indent(this._indentLevel)}else{this.indent();this.print_string(this._ch)}this.eatWhitespace(true);this._output.add_new_line()}else if(this._ch==="}"){this.outdent();this._output.add_new_line();if(previous_ch==="{"){this._output.trim(true)}insideAtImport=false;insideAtExtend=false;if(insidePropertyValue){this.outdent();insidePropertyValue=false}this.print_string(this._ch);insideRule=false;if(this._nestedLevel){this._nestedLevel--}this.eatWhitespace(true);this._output.add_new_line();if(this._options.newline_between_rules&&!this._output.just_added_blankline()){if(this._input.peek()!=="}"){this._output.add_new_line(true)}}}else if(this._ch===":"){if((insideRule||enteringConditionalGroup)&&!(this._input.lookBack("&")||this.foundNestedPseudoClass())&&!this._input.lookBack("(")&&!insideAtExtend&&parenLevel===0){this.print_string(":");if(!insidePropertyValue){insidePropertyValue=true;this._output.space_before_token=true;this.eatWhitespace(true);this.indent()}}else{if(this._input.lookBack(" ")){this._output.space_before_token=true}if(this._input.peek()===":"){this._ch=this._input.next();this.print_string("::")}else{this.print_string(":")}}}else if(this._ch==='"'||this._ch==="'"){this.preserveSingleSpace(isAfterSpace);this.print_string(this._ch+this.eatString(this._ch));this.eatWhitespace(true)}else if(this._ch===";"){if(parenLevel===0){if(insidePropertyValue){this.outdent();insidePropertyValue=false}insideAtExtend=false;insideAtImport=false;this.print_string(this._ch);this.eatWhitespace(true);if(this._input.peek()!=="/"){this._output.add_new_line()}}else{this.print_string(this._ch);this.eatWhitespace(true);this._output.space_before_token=true}}else if(this._ch==="("){if(this._input.lookBack("url")){this.print_string(this._ch);this.eatWhitespace();parenLevel++;this.indent();this._ch=this._input.next();if(this._ch===")"||this._ch==='"'||this._ch==="'"){this._input.back()}else if(this._ch){this.print_string(this._ch+this.eatString(")"));if(parenLevel){parenLevel--;this.outdent()}}}else{this.preserveSingleSpace(isAfterSpace);this.print_string(this._ch);this.eatWhitespace();parenLevel++;this.indent()}}else if(this._ch===")"){if(parenLevel){parenLevel--;this.outdent()}this.print_string(this._ch)}else if(this._ch===","){this.print_string(this._ch);this.eatWhitespace(true);if(this._options.selector_separator_newline&&!insidePropertyValue&&parenLevel===0&&!insideAtImport&&!insideAtExtend){this._output.add_new_line()}else{this._output.space_before_token=true}}else if((this._ch===">"||this._ch==="+"||this._ch==="~")&&!insidePropertyValue&&parenLevel===0){if(this._options.space_around_combinator){this._output.space_before_token=true;this.print_string(this._ch);this._output.space_before_token=true}else{this.print_string(this._ch);this.eatWhitespace();if(this._ch&&whitespaceChar.test(this._ch)){this._ch=""}}}else if(this._ch==="]"){this.print_string(this._ch)}else if(this._ch==="["){this.preserveSingleSpace(isAfterSpace);this.print_string(this._ch)}else if(this._ch==="="){this.eatWhitespace();this.print_string("=");if(whitespaceChar.test(this._ch)){this._ch=""}}else if(this._ch==="!"&&!this._input.lookBack("\\")){this.print_string(" ");this.print_string(this._ch)}else{this.preserveSingleSpace(isAfterSpace);this.print_string(this._ch)}}var sweetCode=this._output.get_code(eol);return sweetCode};module.exports.Beautifier=Beautifier},{"../core/directives":117,"../core/inputscanner":118,"../core/output":120,"./options":129}],128:[function(require,module,exports){"use strict";var Beautifier=require("./beautifier").Beautifier,Options=require("./options").Options;function css_beautify(source_text,options){var beautifier=new Beautifier(source_text,options);return beautifier.beautify()}module.exports=css_beautify;module.exports.defaultOptions=function(){return new Options}},{"./beautifier":127,"./options":129}],129:[function(require,module,exports){"use strict";var BaseOptions=require("../core/options").Options;function Options(options){BaseOptions.call(this,options,"css");this.selector_separator_newline=this._get_boolean("selector_separator_newline",true);this.newline_between_rules=this._get_boolean("newline_between_rules",true);var space_around_selector_separator=this._get_boolean("space_around_selector_separator");this.space_around_combinator=this._get_boolean("space_around_combinator")||space_around_selector_separator;var brace_style_split=this._get_selection_list("brace_style",["collapse","expand","end-expand","none","preserve-inline"]);this.brace_style="collapse";for(var bs=0;bs0)}return newlines!==0};Printer.prototype.traverse_whitespace=function(raw_token){if(raw_token.whitespace_before||raw_token.newlines){if(!this.print_preserved_newlines(raw_token)){this._output.space_before_token=true}return true}return false};Printer.prototype.previous_token_wrapped=function(){return this._output.previous_token_wrapped};Printer.prototype.print_newline=function(force){this._output.add_new_line(force)};Printer.prototype.print_token=function(token){if(token.text){this._output.set_indent(this.indent_level,this.alignment_size);this._output.add_token(token.text)}};Printer.prototype.indent=function(){this.indent_level++};Printer.prototype.get_full_indent=function(level){level=this.indent_level+(level||0);if(level<1){return""}return this._output.get_indent_string(level)};var get_type_attribute=function(start_token){var result=null;var raw_token=start_token.next;while(raw_token.type!==TOKEN.EOF&&start_token.closed!==raw_token){if(raw_token.type===TOKEN.ATTRIBUTE&&raw_token.text==="type"){if(raw_token.next&&raw_token.next.type===TOKEN.EQUALS&&raw_token.next.next&&raw_token.next.next.type===TOKEN.VALUE){result=raw_token.next.next.text}break}raw_token=raw_token.next}return result};var get_custom_beautifier_name=function(tag_check,raw_token){var typeAttribute=null;var result=null;if(!raw_token.closed){return null}if(tag_check==="script"){typeAttribute="text/javascript"}else if(tag_check==="style"){typeAttribute="text/css"}typeAttribute=get_type_attribute(raw_token)||typeAttribute;if(typeAttribute.search("text/css")>-1){result="css"}else if(typeAttribute.search(/module|((text|application|dojo)\/(x-)?(javascript|ecmascript|jscript|livescript|(ld\+)?json|method|aspect))/)>-1){result="javascript"}else if(typeAttribute.search(/(text|application|dojo)\/(x-)?(html)/)>-1){result="html"}else if(typeAttribute.search(/test\/null/)>-1){result="null"}return result};function in_array(what,arr){return arr.indexOf(what)!==-1}function TagFrame(parent,parser_token,indent_level){this.parent=parent||null;this.tag=parser_token?parser_token.tag_name:"";this.indent_level=indent_level||0;this.parser_token=parser_token||null}function TagStack(printer){this._printer=printer;this._current_frame=null}TagStack.prototype.get_parser_token=function(){return this._current_frame?this._current_frame.parser_token:null};TagStack.prototype.record_tag=function(parser_token){var new_frame=new TagFrame(this._current_frame,parser_token,this._printer.indent_level);this._current_frame=new_frame};TagStack.prototype._try_pop_frame=function(frame){var parser_token=null;if(frame){parser_token=frame.parser_token;this._printer.indent_level=frame.indent_level;this._current_frame=frame.parent}return parser_token};TagStack.prototype._get_frame=function(tag_list,stop_list){var frame=this._current_frame;while(frame){if(tag_list.indexOf(frame.tag)!==-1){break}else if(stop_list&&stop_list.indexOf(frame.tag)!==-1){frame=null;break}frame=frame.parent}return frame};TagStack.prototype.try_pop=function(tag,stop_list){var frame=this._get_frame([tag],stop_list);return this._try_pop_frame(frame)};TagStack.prototype.indent_to_tag=function(tag_list){var frame=this._get_frame(tag_list);if(frame){this._printer.indent_level=frame.indent_level}};function Beautifier(source_text,options,js_beautify,css_beautify){this._source_text=source_text||"";options=options||{};this._js_beautify=js_beautify;this._css_beautify=css_beautify;this._tag_stack=null;var optionHtml=new Options(options,"html");this._options=optionHtml;this._is_wrap_attributes_force=this._options.wrap_attributes.substr(0,"force".length)==="force";this._is_wrap_attributes_force_expand_multiline=this._options.wrap_attributes==="force-expand-multiline";this._is_wrap_attributes_force_aligned=this._options.wrap_attributes==="force-aligned";this._is_wrap_attributes_aligned_multiple=this._options.wrap_attributes==="aligned-multiple";this._is_wrap_attributes_preserve=this._options.wrap_attributes.substr(0,"preserve".length)==="preserve";this._is_wrap_attributes_preserve_aligned=this._options.wrap_attributes==="preserve-aligned"}Beautifier.prototype.beautify=function(){if(this._options.disabled){return this._source_text}var source_text=this._source_text;var eol=this._options.eol;if(this._options.eol==="auto"){eol="\n";if(source_text&&lineBreak.test(source_text)){eol=source_text.match(lineBreak)[0]}}source_text=source_text.replace(allLineBreaks,"\n");var baseIndentString=source_text.match(/^[\t ]*/)[0];var last_token={text:"",type:""};var last_tag_token=new TagOpenParserToken;var printer=new Printer(this._options,baseIndentString);var tokens=new Tokenizer(source_text,this._options).tokenize();this._tag_stack=new TagStack(printer);var parser_token=null;var raw_token=tokens.next();while(raw_token.type!==TOKEN.EOF){if(raw_token.type===TOKEN.TAG_OPEN||raw_token.type===TOKEN.COMMENT){parser_token=this._handle_tag_open(printer,raw_token,last_tag_token,last_token);last_tag_token=parser_token}else if(raw_token.type===TOKEN.ATTRIBUTE||raw_token.type===TOKEN.EQUALS||raw_token.type===TOKEN.VALUE||raw_token.type===TOKEN.TEXT&&!last_tag_token.tag_complete){parser_token=this._handle_inside_tag(printer,raw_token,last_tag_token,tokens)}else if(raw_token.type===TOKEN.TAG_CLOSE){parser_token=this._handle_tag_close(printer,raw_token,last_tag_token)}else if(raw_token.type===TOKEN.TEXT){parser_token=this._handle_text(printer,raw_token,last_tag_token)}else{printer.add_raw_token(raw_token)}last_token=parser_token;raw_token=tokens.next()}var sweet_code=printer._output.get_code(eol);return sweet_code};Beautifier.prototype._handle_tag_close=function(printer,raw_token,last_tag_token){var parser_token={text:raw_token.text,type:raw_token.type};printer.alignment_size=0;last_tag_token.tag_complete=true;printer.set_space_before_token(raw_token.newlines||raw_token.whitespace_before!=="",true);if(last_tag_token.is_unformatted){printer.add_raw_token(raw_token)}else{if(last_tag_token.tag_start_char==="<"){printer.set_space_before_token(raw_token.text[0]==="/",true);if(this._is_wrap_attributes_force_expand_multiline&&last_tag_token.has_wrapped_attrs){printer.print_newline(false)}}printer.print_token(raw_token)}if(last_tag_token.indent_content&&!(last_tag_token.is_unformatted||last_tag_token.is_content_unformatted)){printer.indent();last_tag_token.indent_content=false}if(!last_tag_token.is_inline_element&&!(last_tag_token.is_unformatted||last_tag_token.is_content_unformatted)){printer.set_wrap_point()}return parser_token};Beautifier.prototype._handle_inside_tag=function(printer,raw_token,last_tag_token,tokens){var wrapped=last_tag_token.has_wrapped_attrs;var parser_token={text:raw_token.text,type:raw_token.type};printer.set_space_before_token(raw_token.newlines||raw_token.whitespace_before!=="",true);if(last_tag_token.is_unformatted){printer.add_raw_token(raw_token)}else if(last_tag_token.tag_start_char==="{"&&raw_token.type===TOKEN.TEXT){if(printer.print_preserved_newlines(raw_token)){raw_token.newlines=0;printer.add_raw_token(raw_token)}else{printer.print_token(raw_token)}}else{if(raw_token.type===TOKEN.ATTRIBUTE){printer.set_space_before_token(true);last_tag_token.attr_count+=1}else if(raw_token.type===TOKEN.EQUALS){printer.set_space_before_token(false)}else if(raw_token.type===TOKEN.VALUE&&raw_token.previous.type===TOKEN.EQUALS){printer.set_space_before_token(false)}if(raw_token.type===TOKEN.ATTRIBUTE&&last_tag_token.tag_start_char==="<"){if(this._is_wrap_attributes_preserve||this._is_wrap_attributes_preserve_aligned){printer.traverse_whitespace(raw_token);wrapped=wrapped||raw_token.newlines!==0}if(this._is_wrap_attributes_force){var force_attr_wrap=last_tag_token.attr_count>1;if(this._is_wrap_attributes_force_expand_multiline&&last_tag_token.attr_count===1){var is_only_attribute=true;var peek_index=0;var peek_token;do{peek_token=tokens.peek(peek_index);if(peek_token.type===TOKEN.ATTRIBUTE){is_only_attribute=false;break}peek_index+=1}while(peek_index<4&&peek_token.type!==TOKEN.EOF&&peek_token.type!==TOKEN.TAG_CLOSE);force_attr_wrap=!is_only_attribute}if(force_attr_wrap){printer.print_newline(false);wrapped=true}}}printer.print_token(raw_token);wrapped=wrapped||printer.previous_token_wrapped();last_tag_token.has_wrapped_attrs=wrapped}return parser_token};Beautifier.prototype._handle_text=function(printer,raw_token,last_tag_token){var parser_token={text:raw_token.text,type:"TK_CONTENT"};if(last_tag_token.custom_beautifier_name){this._print_custom_beatifier_text(printer,raw_token,last_tag_token)}else if(last_tag_token.is_unformatted||last_tag_token.is_content_unformatted){printer.add_raw_token(raw_token)}else{printer.traverse_whitespace(raw_token);printer.print_token(raw_token)}return parser_token};Beautifier.prototype._print_custom_beatifier_text=function(printer,raw_token,last_tag_token){var local=this;if(raw_token.text!==""){var text=raw_token.text,_beautifier,script_indent_level=1,pre="",post="";if(last_tag_token.custom_beautifier_name==="javascript"&&typeof this._js_beautify==="function"){_beautifier=this._js_beautify}else if(last_tag_token.custom_beautifier_name==="css"&&typeof this._css_beautify==="function"){_beautifier=this._css_beautify}else if(last_tag_token.custom_beautifier_name==="html"){_beautifier=function(html_source,options){var beautifier=new Beautifier(html_source,options,local._js_beautify,local._css_beautify);return beautifier.beautify()}}if(this._options.indent_scripts==="keep"){script_indent_level=0}else if(this._options.indent_scripts==="separate"){script_indent_level=-printer.indent_level}var indentation=printer.get_full_indent(script_indent_level);text=text.replace(/\n[ \t]*$/,"");if(last_tag_token.custom_beautifier_name!=="html"&&text[0]==="<"&&text.match(/^(|]]>)$/.exec(text);if(!matched){printer.add_raw_token(raw_token);return}pre=indentation+matched[1]+"\n";text=matched[4];if(matched[5]){post=indentation+matched[5]}text=text.replace(/\n[ \t]*$/,"");if(matched[2]||matched[3].indexOf("\n")!==-1){matched=matched[3].match(/[ \t]+$/);if(matched){raw_token.whitespace_before=matched[0]}}}if(text){if(_beautifier){var Child_options=function(){this.eol="\n"};Child_options.prototype=this._options.raw_options;var child_options=new Child_options;text=_beautifier(indentation+text,child_options)}else{var white=raw_token.whitespace_before;if(white){text=text.replace(new RegExp("\n("+white+")?","g"),"\n")}text=indentation+text.replace(/\n/g,"\n"+indentation)}}if(pre){if(!text){text=pre+post}else{text=pre+text+"\n"+post}}printer.print_newline(false);if(text){raw_token.text=text;raw_token.whitespace_before="";raw_token.newlines=0;printer.add_raw_token(raw_token);printer.print_newline(true)}}};Beautifier.prototype._handle_tag_open=function(printer,raw_token,last_tag_token,last_token){var parser_token=this._get_tag_open_token(raw_token);if((last_tag_token.is_unformatted||last_tag_token.is_content_unformatted)&&!last_tag_token.is_empty_element&&raw_token.type===TOKEN.TAG_OPEN&&raw_token.text.indexOf("]*)/);this.tag_check=tag_check_match?tag_check_match[1]:""}else{tag_check_match=raw_token.text.match(/^{{(?:[\^]|#\*?)?([^\s}]+)/);this.tag_check=tag_check_match?tag_check_match[1]:"";if(raw_token.text==="{{#>"&&this.tag_check===">"&&raw_token.next!==null){this.tag_check=raw_token.next.text}}this.tag_check=this.tag_check.toLowerCase();if(raw_token.type===TOKEN.COMMENT){this.tag_complete=true}this.is_start_tag=this.tag_check.charAt(0)!=="/";this.tag_name=!this.is_start_tag?this.tag_check.substr(1):this.tag_check;this.is_end_tag=!this.is_start_tag||raw_token.closed&&raw_token.closed.text==="/>";this.is_end_tag=this.is_end_tag||this.tag_start_char==="{"&&(this.text.length<3||/[^#\^]/.test(this.text.charAt(2)))}};Beautifier.prototype._get_tag_open_token=function(raw_token){var parser_token=new TagOpenParserToken(this._tag_stack.get_parser_token(),raw_token);parser_token.alignment_size=this._options.wrap_attributes_indent_size;parser_token.is_end_tag=parser_token.is_end_tag||in_array(parser_token.tag_check,this._options.void_elements);parser_token.is_empty_element=parser_token.tag_complete||parser_token.is_start_tag&&parser_token.is_end_tag;parser_token.is_unformatted=!parser_token.tag_complete&&in_array(parser_token.tag_check,this._options.unformatted);parser_token.is_content_unformatted=!parser_token.is_empty_element&&in_array(parser_token.tag_check,this._options.content_unformatted);parser_token.is_inline_element=in_array(parser_token.tag_name,this._options.inline)||parser_token.tag_start_char==="{";return parser_token};Beautifier.prototype._set_tag_position=function(printer,raw_token,parser_token,last_tag_token,last_token){if(!parser_token.is_empty_element){if(parser_token.is_end_tag){parser_token.start_tag_token=this._tag_stack.try_pop(parser_token.tag_name)}else{if(this._do_optional_end_element(parser_token)){if(!parser_token.is_inline_element){printer.print_newline(false)}}this._tag_stack.record_tag(parser_token);if((parser_token.tag_name==="script"||parser_token.tag_name==="style")&&!(parser_token.is_unformatted||parser_token.is_content_unformatted)){parser_token.custom_beautifier_name=get_custom_beautifier_name(parser_token.tag_check,raw_token)}}}if(in_array(parser_token.tag_check,this._options.extra_liners)){printer.print_newline(false);if(!printer._output.just_added_blankline()){printer.print_newline(true)}}if(parser_token.is_empty_element){if(parser_token.tag_start_char==="{"&&parser_token.tag_check==="else"){this._tag_stack.indent_to_tag(["if","unless","each"]);parser_token.indent_content=true;var foundIfOnCurrentLine=printer.current_line_has_match(/{{#if/);if(!foundIfOnCurrentLine){printer.print_newline(false)}}if(parser_token.tag_name==="!--"&&last_token.type===TOKEN.TAG_CLOSE&&last_tag_token.is_end_tag&&parser_token.text.indexOf("\n")===-1){}else{if(!(parser_token.is_inline_element||parser_token.is_unformatted)){printer.print_newline(false)}this._calcluate_parent_multiline(printer,parser_token)}}else if(parser_token.is_end_tag){var do_end_expand=false;do_end_expand=parser_token.start_tag_token&&parser_token.start_tag_token.multiline_content;do_end_expand=do_end_expand||!parser_token.is_inline_element&&!(last_tag_token.is_inline_element||last_tag_token.is_unformatted)&&!(last_token.type===TOKEN.TAG_CLOSE&&parser_token.start_tag_token===last_tag_token)&&last_token.type!=="TK_CONTENT";if(parser_token.is_content_unformatted||parser_token.is_unformatted){do_end_expand=false}if(do_end_expand){printer.print_newline(false)}}else{parser_token.indent_content=!parser_token.custom_beautifier_name;if(parser_token.tag_start_char==="<"){if(parser_token.tag_name==="html"){parser_token.indent_content=this._options.indent_inner_html}else if(parser_token.tag_name==="head"){parser_token.indent_content=this._options.indent_head_inner_html}else if(parser_token.tag_name==="body"){parser_token.indent_content=this._options.indent_body_inner_html}}if(!(parser_token.is_inline_element||parser_token.is_unformatted)&&(last_token.type!=="TK_CONTENT"||parser_token.is_content_unformatted)){printer.print_newline(false)}this._calcluate_parent_multiline(printer,parser_token)}};Beautifier.prototype._calcluate_parent_multiline=function(printer,parser_token){if(parser_token.parent&&printer._output.just_added_newline()&&!((parser_token.is_inline_element||parser_token.is_unformatted)&&parser_token.parent.is_inline_element)){parser_token.parent.multiline_content=true}};var p_closers=["address","article","aside","blockquote","details","div","dl","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","header","hr","main","nav","ol","p","pre","section","table","ul"];var p_parent_excludes=["a","audio","del","ins","map","noscript","video"];Beautifier.prototype._do_optional_end_element=function(parser_token){var result=null;if(parser_token.is_empty_element||!parser_token.is_start_tag||!parser_token.parent){return}if(parser_token.tag_name==="body"){result=result||this._tag_stack.try_pop("head")}else if(parser_token.tag_name==="li"){result=result||this._tag_stack.try_pop("li",["ol","ul"])}else if(parser_token.tag_name==="dd"||parser_token.tag_name==="dt"){result=result||this._tag_stack.try_pop("dt",["dl"]);result=result||this._tag_stack.try_pop("dd",["dl"])}else if(parser_token.parent.tag_name==="p"&&p_closers.indexOf(parser_token.tag_name)!==-1){var p_parent=parser_token.parent.parent;if(!p_parent||p_parent_excludes.indexOf(p_parent.tag_name)===-1){result=result||this._tag_stack.try_pop("p")}}else if(parser_token.tag_name==="rp"||parser_token.tag_name==="rt"){result=result||this._tag_stack.try_pop("rt",["ruby","rtc"]);result=result||this._tag_stack.try_pop("rp",["ruby","rtc"])}else if(parser_token.tag_name==="optgroup"){result=result||this._tag_stack.try_pop("optgroup",["select"])}else if(parser_token.tag_name==="option"){result=result||this._tag_stack.try_pop("option",["select","datalist","optgroup"])}else if(parser_token.tag_name==="colgroup"){result=result||this._tag_stack.try_pop("caption",["table"])}else if(parser_token.tag_name==="thead"){result=result||this._tag_stack.try_pop("caption",["table"]);result=result||this._tag_stack.try_pop("colgroup",["table"])}else if(parser_token.tag_name==="tbody"||parser_token.tag_name==="tfoot"){result=result||this._tag_stack.try_pop("caption",["table"]);result=result||this._tag_stack.try_pop("colgroup",["table"]);result=result||this._tag_stack.try_pop("thead",["table"]);result=result||this._tag_stack.try_pop("tbody",["table"])}else if(parser_token.tag_name==="tr"){result=result||this._tag_stack.try_pop("caption",["table"]);result=result||this._tag_stack.try_pop("colgroup",["table"]);result=result||this._tag_stack.try_pop("tr",["table","thead","tbody","tfoot"])}else if(parser_token.tag_name==="th"||parser_token.tag_name==="td"){result=result||this._tag_stack.try_pop("td",["table","thead","tbody","tfoot","tr"]);result=result||this._tag_stack.try_pop("th",["table","thead","tbody","tfoot","tr"])}parser_token.parent=this._tag_stack.get_parser_token();return result};module.exports.Beautifier=Beautifier},{"../core/output":120,"../html/options":132,"../html/tokenizer":133}],131:[function(require,module,exports){"use strict";var Beautifier=require("./beautifier").Beautifier,Options=require("./options").Options;function style_html(html_source,options,js_beautify,css_beautify){var beautifier=new Beautifier(html_source,options,js_beautify,css_beautify);return beautifier.beautify()}module.exports=style_html;module.exports.defaultOptions=function(){return new Options}},{"./beautifier":130,"./options":132}],132:[function(require,module,exports){"use strict";var BaseOptions=require("../core/options").Options;function Options(options){BaseOptions.call(this,options,"html");if(this.templating.length===1&&this.templating[0]==="auto"){this.templating=["django","erb","handlebars","php"]}this.indent_inner_html=this._get_boolean("indent_inner_html");this.indent_body_inner_html=this._get_boolean("indent_body_inner_html",true);this.indent_head_inner_html=this._get_boolean("indent_head_inner_html",true);this.indent_handlebars=this._get_boolean("indent_handlebars",true);this.wrap_attributes=this._get_selection("wrap_attributes",["auto","force","force-aligned","force-expand-multiline","aligned-multiple","preserve","preserve-aligned"]);this.wrap_attributes_indent_size=this._get_number("wrap_attributes_indent_size",this.indent_size);this.extra_liners=this._get_array("extra_liners",["head","body","/html"]);this.inline=this._get_array("inline",["a","abbr","area","audio","b","bdi","bdo","br","button","canvas","cite","code","data","datalist","del","dfn","em","embed","i","iframe","img","input","ins","kbd","keygen","label","map","mark","math","meter","noscript","object","output","progress","q","ruby","s","samp","select","small","span","strong","sub","sup","svg","template","textarea","time","u","var","video","wbr","text","acronym","big","strike","tt"]);this.void_elements=this._get_array("void_elements",["area","base","br","col","embed","hr","img","input","keygen","link","menuitem","meta","param","source","track","wbr","!doctype","?xml","basefont","isindex"]);this.unformatted=this._get_array("unformatted",[]);this.content_unformatted=this._get_array("content_unformatted",["pre","textarea"]);this.unformatted_content_delimiter=this._get_characters("unformatted_content_delimiter");this.indent_scripts=this._get_selection("indent_scripts",["normal","keep","separate"])}Options.prototype=new BaseOptions;module.exports.Options=Options},{"../core/options":119}],133:[function(require,module,exports){"use strict";var BaseTokenizer=require("../core/tokenizer").Tokenizer;var BASETOKEN=require("../core/tokenizer").TOKEN;var Directives=require("../core/directives").Directives;var TemplatablePattern=require("../core/templatablepattern").TemplatablePattern;var Pattern=require("../core/pattern").Pattern;var TOKEN={TAG_OPEN:"TK_TAG_OPEN",TAG_CLOSE:"TK_TAG_CLOSE",ATTRIBUTE:"TK_ATTRIBUTE",EQUALS:"TK_EQUALS",VALUE:"TK_VALUE",COMMENT:"TK_COMMENT",TEXT:"TK_TEXT",UNKNOWN:"TK_UNKNOWN",START:BASETOKEN.START,RAW:BASETOKEN.RAW,EOF:BASETOKEN.EOF};var directives_core=new Directives(/<\!--/,/-->/);var Tokenizer=function(input_string,options){BaseTokenizer.call(this,input_string,options);this._current_tag_name="";var templatable_reader=new TemplatablePattern(this._input).read_options(this._options);var pattern_reader=new Pattern(this._input);this.__patterns={word:templatable_reader.until(/[\n\r\t <]/),single_quote:templatable_reader.until_after(/'/),double_quote:templatable_reader.until_after(/"/),attribute:templatable_reader.until(/[\n\r\t =>]|\/>/),element_name:templatable_reader.until(/[\n\r\t >\/]/),handlebars_comment:pattern_reader.starting_with(/{{!--/).until_after(/--}}/),handlebars:pattern_reader.starting_with(/{{/).until_after(/}}/),handlebars_open:pattern_reader.until(/[\n\r\t }]/),handlebars_raw_close:pattern_reader.until(/}}/),comment:pattern_reader.starting_with(//),cdata:pattern_reader.starting_with(//),conditional_comment:pattern_reader.starting_with(//),processing:pattern_reader.starting_with(/<\?/).until_after(/\?>/)};if(this._options.indent_handlebars){this.__patterns.word=this.__patterns.word.exclude("handlebars")}this._unformatted_content_delimiter=null;if(this._options.unformatted_content_delimiter){var literal_regexp=this._input.get_literal_regexp(this._options.unformatted_content_delimiter);this.__patterns.unformatted_content_delimiter=pattern_reader.matching(literal_regexp).until_after(literal_regexp)}};Tokenizer.prototype=new BaseTokenizer;Tokenizer.prototype._is_comment=function(current_token){return false};Tokenizer.prototype._is_opening=function(current_token){return current_token.type===TOKEN.TAG_OPEN};Tokenizer.prototype._is_closing=function(current_token,open_token){return current_token.type===TOKEN.TAG_CLOSE&&(open_token&&((current_token.text===">"||current_token.text==="/>")&&open_token.text[0]==="<"||current_token.text==="}}"&&open_token.text[0]==="{"&&open_token.text[1]==="{"))};Tokenizer.prototype._reset=function(){this._current_tag_name=""};Tokenizer.prototype._get_next_token=function(previous_token,open_token){var token=null;this._readWhitespace();var c=this._input.peek();if(c===null){return this._create_token(TOKEN.EOF,"")}token=token||this._read_open_handlebars(c,open_token);token=token||this._read_attribute(c,previous_token,open_token);token=token||this._read_close(c,open_token);token=token||this._read_raw_content(c,previous_token,open_token);token=token||this._read_content_word(c);token=token||this._read_comment_or_cdata(c);token=token||this._read_processing(c);token=token||this._read_open(c,open_token);token=token||this._create_token(TOKEN.UNKNOWN,this._input.next());return token};Tokenizer.prototype._read_comment_or_cdata=function(c){var token=null;var resulting_string=null;var directives=null;if(c==="<"){var peek1=this._input.peek(1);if(peek1==="!"){resulting_string=this.__patterns.comment.read();if(resulting_string){directives=directives_core.get_directives(resulting_string);if(directives&&directives.ignore==="start"){resulting_string+=directives_core.readIgnored(this._input)}}else{resulting_string=this.__patterns.cdata.read()}}if(resulting_string){token=this._create_token(TOKEN.COMMENT,resulting_string);token.directives=directives}}return token};Tokenizer.prototype._read_processing=function(c){var token=null;var resulting_string=null;var directives=null;if(c==="<"){var peek1=this._input.peek(1);if(peek1==="!"||peek1==="?"){resulting_string=this.__patterns.conditional_comment.read();resulting_string=resulting_string||this.__patterns.processing.read()}if(resulting_string){token=this._create_token(TOKEN.COMMENT,resulting_string);token.directives=directives}}return token};Tokenizer.prototype._read_open=function(c,open_token){var resulting_string=null;var token=null;if(!open_token){if(c==="<"){resulting_string=this._input.next();if(this._input.peek()==="/"){resulting_string+=this._input.next()}resulting_string+=this.__patterns.element_name.read();token=this._create_token(TOKEN.TAG_OPEN,resulting_string)}}return token};Tokenizer.prototype._read_open_handlebars=function(c,open_token){var resulting_string=null;var token=null;if(!open_token){if(this._options.indent_handlebars&&c==="{"&&this._input.peek(1)==="{"){if(this._input.peek(2)==="!"){resulting_string=this.__patterns.handlebars_comment.read();resulting_string=resulting_string||this.__patterns.handlebars.read();token=this._create_token(TOKEN.COMMENT,resulting_string)}else{resulting_string=this.__patterns.handlebars_open.read();token=this._create_token(TOKEN.TAG_OPEN,resulting_string)}}}return token};Tokenizer.prototype._read_close=function(c,open_token){var resulting_string=null;var token=null;if(open_token){if(open_token.text[0]==="<"&&(c===">"||c==="/"&&this._input.peek(1)===">")){resulting_string=this._input.next();if(c==="/"){resulting_string+=this._input.next()}token=this._create_token(TOKEN.TAG_CLOSE,resulting_string)}else if(open_token.text[0]==="{"&&c==="}"&&this._input.peek(1)==="}"){this._input.next();this._input.next();token=this._create_token(TOKEN.TAG_CLOSE,"}}")}}return token};Tokenizer.prototype._read_attribute=function(c,previous_token,open_token){var token=null;var resulting_string="";if(open_token&&open_token.text[0]==="<"){if(c==="="){token=this._create_token(TOKEN.EQUALS,this._input.next())}else if(c==='"'||c==="'"){var content=this._input.next();if(c==='"'){content+=this.__patterns.double_quote.read()}else{content+=this.__patterns.single_quote.read()}token=this._create_token(TOKEN.VALUE,content)}else{resulting_string=this.__patterns.attribute.read();if(resulting_string){if(previous_token.type===TOKEN.EQUALS){token=this._create_token(TOKEN.VALUE,resulting_string)}else{token=this._create_token(TOKEN.ATTRIBUTE,resulting_string)}}}}return token};Tokenizer.prototype._is_content_unformatted=function(tag_name){return this._options.void_elements.indexOf(tag_name)===-1&&(this._options.content_unformatted.indexOf(tag_name)!==-1||this._options.unformatted.indexOf(tag_name)!==-1)};Tokenizer.prototype._read_raw_content=function(c,previous_token,open_token){var resulting_string="";if(open_token&&open_token.text[0]==="{"){resulting_string=this.__patterns.handlebars_raw_close.read()}else if(previous_token.type===TOKEN.TAG_CLOSE&&previous_token.opened.text[0]==="<"&&previous_token.text[0]!=="/"){var tag_name=previous_token.opened.text.substr(1).toLowerCase();if(tag_name==="script"||tag_name==="style"){var token=this._read_comment_or_cdata(c);if(token){token.type=TOKEN.TEXT;return token}resulting_string=this._input.readUntil(new RegExp("","ig"))}else if(this._is_content_unformatted(tag_name)){resulting_string=this._input.readUntil(new RegExp("","ig"))}}if(resulting_string){return this._create_token(TOKEN.TEXT,resulting_string)}return null};Tokenizer.prototype._read_content_word=function(c){var resulting_string="";if(this._options.unformatted_content_delimiter){if(c===this._options.unformatted_content_delimiter[0]){resulting_string=this.__patterns.unformatted_content_delimiter.read()}}if(!resulting_string){resulting_string=this.__patterns.word.read()}if(resulting_string){return this._create_token(TOKEN.TEXT,resulting_string)}};module.exports.Tokenizer=Tokenizer;module.exports.TOKEN=TOKEN},{"../core/directives":117,"../core/pattern":121,"../core/templatablepattern":122,"../core/tokenizer":124}],134:[function(require,module,exports){"use strict";var js_beautify=require("./javascript/index");var css_beautify=require("./css/index");var html_beautify=require("./html/index");function style_html(html_source,options,js,css){js=js||js_beautify;css=css||css_beautify;return html_beautify(html_source,options,js,css)}style_html.defaultOptions=html_beautify.defaultOptions;module.exports.js=js_beautify;module.exports.css=css_beautify;module.exports.html=style_html},{"./css/index":128,"./html/index":131,"./javascript/index":137}],135:[function(require,module,exports){"use strict";var baseASCIIidentifierStartChars="\\x23\\x24\\x40\\x41-\\x5a\\x5f\\x61-\\x7a";var baseASCIIidentifierChars="\\x24\\x30-\\x39\\x41-\\x5a\\x5f\\x61-\\x7a";var nonASCIIidentifierStartChars="\\xaa\\xb5\\xba\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\u02c1\\u02c6-\\u02d1\\u02e0-\\u02e4\\u02ec\\u02ee\\u0370-\\u0374\\u0376\\u0377\\u037a-\\u037d\\u0386\\u0388-\\u038a\\u038c\\u038e-\\u03a1\\u03a3-\\u03f5\\u03f7-\\u0481\\u048a-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05d0-\\u05ea\\u05f0-\\u05f2\\u0620-\\u064a\\u066e\\u066f\\u0671-\\u06d3\\u06d5\\u06e5\\u06e6\\u06ee\\u06ef\\u06fa-\\u06fc\\u06ff\\u0710\\u0712-\\u072f\\u074d-\\u07a5\\u07b1\\u07ca-\\u07ea\\u07f4\\u07f5\\u07fa\\u0800-\\u0815\\u081a\\u0824\\u0828\\u0840-\\u0858\\u08a0\\u08a2-\\u08ac\\u0904-\\u0939\\u093d\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097f\\u0985-\\u098c\\u098f\\u0990\\u0993-\\u09a8\\u09aa-\\u09b0\\u09b2\\u09b6-\\u09b9\\u09bd\\u09ce\\u09dc\\u09dd\\u09df-\\u09e1\\u09f0\\u09f1\\u0a05-\\u0a0a\\u0a0f\\u0a10\\u0a13-\\u0a28\\u0a2a-\\u0a30\\u0a32\\u0a33\\u0a35\\u0a36\\u0a38\\u0a39\\u0a59-\\u0a5c\\u0a5e\\u0a72-\\u0a74\\u0a85-\\u0a8d\\u0a8f-\\u0a91\\u0a93-\\u0aa8\\u0aaa-\\u0ab0\\u0ab2\\u0ab3\\u0ab5-\\u0ab9\\u0abd\\u0ad0\\u0ae0\\u0ae1\\u0b05-\\u0b0c\\u0b0f\\u0b10\\u0b13-\\u0b28\\u0b2a-\\u0b30\\u0b32\\u0b33\\u0b35-\\u0b39\\u0b3d\\u0b5c\\u0b5d\\u0b5f-\\u0b61\\u0b71\\u0b83\\u0b85-\\u0b8a\\u0b8e-\\u0b90\\u0b92-\\u0b95\\u0b99\\u0b9a\\u0b9c\\u0b9e\\u0b9f\\u0ba3\\u0ba4\\u0ba8-\\u0baa\\u0bae-\\u0bb9\\u0bd0\\u0c05-\\u0c0c\\u0c0e-\\u0c10\\u0c12-\\u0c28\\u0c2a-\\u0c33\\u0c35-\\u0c39\\u0c3d\\u0c58\\u0c59\\u0c60\\u0c61\\u0c85-\\u0c8c\\u0c8e-\\u0c90\\u0c92-\\u0ca8\\u0caa-\\u0cb3\\u0cb5-\\u0cb9\\u0cbd\\u0cde\\u0ce0\\u0ce1\\u0cf1\\u0cf2\\u0d05-\\u0d0c\\u0d0e-\\u0d10\\u0d12-\\u0d3a\\u0d3d\\u0d4e\\u0d60\\u0d61\\u0d7a-\\u0d7f\\u0d85-\\u0d96\\u0d9a-\\u0db1\\u0db3-\\u0dbb\\u0dbd\\u0dc0-\\u0dc6\\u0e01-\\u0e30\\u0e32\\u0e33\\u0e40-\\u0e46\\u0e81\\u0e82\\u0e84\\u0e87\\u0e88\\u0e8a\\u0e8d\\u0e94-\\u0e97\\u0e99-\\u0e9f\\u0ea1-\\u0ea3\\u0ea5\\u0ea7\\u0eaa\\u0eab\\u0ead-\\u0eb0\\u0eb2\\u0eb3\\u0ebd\\u0ec0-\\u0ec4\\u0ec6\\u0edc-\\u0edf\\u0f00\\u0f40-\\u0f47\\u0f49-\\u0f6c\\u0f88-\\u0f8c\\u1000-\\u102a\\u103f\\u1050-\\u1055\\u105a-\\u105d\\u1061\\u1065\\u1066\\u106e-\\u1070\\u1075-\\u1081\\u108e\\u10a0-\\u10c5\\u10c7\\u10cd\\u10d0-\\u10fa\\u10fc-\\u1248\\u124a-\\u124d\\u1250-\\u1256\\u1258\\u125a-\\u125d\\u1260-\\u1288\\u128a-\\u128d\\u1290-\\u12b0\\u12b2-\\u12b5\\u12b8-\\u12be\\u12c0\\u12c2-\\u12c5\\u12c8-\\u12d6\\u12d8-\\u1310\\u1312-\\u1315\\u1318-\\u135a\\u1380-\\u138f\\u13a0-\\u13f4\\u1401-\\u166c\\u166f-\\u167f\\u1681-\\u169a\\u16a0-\\u16ea\\u16ee-\\u16f0\\u1700-\\u170c\\u170e-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176c\\u176e-\\u1770\\u1780-\\u17b3\\u17d7\\u17dc\\u1820-\\u1877\\u1880-\\u18a8\\u18aa\\u18b0-\\u18f5\\u1900-\\u191c\\u1950-\\u196d\\u1970-\\u1974\\u1980-\\u19ab\\u19c1-\\u19c7\\u1a00-\\u1a16\\u1a20-\\u1a54\\u1aa7\\u1b05-\\u1b33\\u1b45-\\u1b4b\\u1b83-\\u1ba0\\u1bae\\u1baf\\u1bba-\\u1be5\\u1c00-\\u1c23\\u1c4d-\\u1c4f\\u1c5a-\\u1c7d\\u1ce9-\\u1cec\\u1cee-\\u1cf1\\u1cf5\\u1cf6\\u1d00-\\u1dbf\\u1e00-\\u1f15\\u1f18-\\u1f1d\\u1f20-\\u1f45\\u1f48-\\u1f4d\\u1f50-\\u1f57\\u1f59\\u1f5b\\u1f5d\\u1f5f-\\u1f7d\\u1f80-\\u1fb4\\u1fb6-\\u1fbc\\u1fbe\\u1fc2-\\u1fc4\\u1fc6-\\u1fcc\\u1fd0-\\u1fd3\\u1fd6-\\u1fdb\\u1fe0-\\u1fec\\u1ff2-\\u1ff4\\u1ff6-\\u1ffc\\u2071\\u207f\\u2090-\\u209c\\u2102\\u2107\\u210a-\\u2113\\u2115\\u2119-\\u211d\\u2124\\u2126\\u2128\\u212a-\\u212d\\u212f-\\u2139\\u213c-\\u213f\\u2145-\\u2149\\u214e\\u2160-\\u2188\\u2c00-\\u2c2e\\u2c30-\\u2c5e\\u2c60-\\u2ce4\\u2ceb-\\u2cee\\u2cf2\\u2cf3\\u2d00-\\u2d25\\u2d27\\u2d2d\\u2d30-\\u2d67\\u2d6f\\u2d80-\\u2d96\\u2da0-\\u2da6\\u2da8-\\u2dae\\u2db0-\\u2db6\\u2db8-\\u2dbe\\u2dc0-\\u2dc6\\u2dc8-\\u2dce\\u2dd0-\\u2dd6\\u2dd8-\\u2dde\\u2e2f\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303c\\u3041-\\u3096\\u309d-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312d\\u3131-\\u318e\\u31a0-\\u31ba\\u31f0-\\u31ff\\u3400-\\u4db5\\u4e00-\\u9fcc\\ua000-\\ua48c\\ua4d0-\\ua4fd\\ua500-\\ua60c\\ua610-\\ua61f\\ua62a\\ua62b\\ua640-\\ua66e\\ua67f-\\ua697\\ua6a0-\\ua6ef\\ua717-\\ua71f\\ua722-\\ua788\\ua78b-\\ua78e\\ua790-\\ua793\\ua7a0-\\ua7aa\\ua7f8-\\ua801\\ua803-\\ua805\\ua807-\\ua80a\\ua80c-\\ua822\\ua840-\\ua873\\ua882-\\ua8b3\\ua8f2-\\ua8f7\\ua8fb\\ua90a-\\ua925\\ua930-\\ua946\\ua960-\\ua97c\\ua984-\\ua9b2\\ua9cf\\uaa00-\\uaa28\\uaa40-\\uaa42\\uaa44-\\uaa4b\\uaa60-\\uaa76\\uaa7a\\uaa80-\\uaaaf\\uaab1\\uaab5\\uaab6\\uaab9-\\uaabd\\uaac0\\uaac2\\uaadb-\\uaadd\\uaae0-\\uaaea\\uaaf2-\\uaaf4\\uab01-\\uab06\\uab09-\\uab0e\\uab11-\\uab16\\uab20-\\uab26\\uab28-\\uab2e\\uabc0-\\uabe2\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufb00-\\ufb06\\ufb13-\\ufb17\\ufb1d\\ufb1f-\\ufb28\\ufb2a-\\ufb36\\ufb38-\\ufb3c\\ufb3e\\ufb40\\ufb41\\ufb43\\ufb44\\ufb46-\\ufbb1\\ufbd3-\\ufd3d\\ufd50-\\ufd8f\\ufd92-\\ufdc7\\ufdf0-\\ufdfb\\ufe70-\\ufe74\\ufe76-\\ufefc\\uff21-\\uff3a\\uff41-\\uff5a\\uff66-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc";var nonASCIIidentifierChars="\\u0300-\\u036f\\u0483-\\u0487\\u0591-\\u05bd\\u05bf\\u05c1\\u05c2\\u05c4\\u05c5\\u05c7\\u0610-\\u061a\\u0620-\\u0649\\u0672-\\u06d3\\u06e7-\\u06e8\\u06fb-\\u06fc\\u0730-\\u074a\\u0800-\\u0814\\u081b-\\u0823\\u0825-\\u0827\\u0829-\\u082d\\u0840-\\u0857\\u08e4-\\u08fe\\u0900-\\u0903\\u093a-\\u093c\\u093e-\\u094f\\u0951-\\u0957\\u0962-\\u0963\\u0966-\\u096f\\u0981-\\u0983\\u09bc\\u09be-\\u09c4\\u09c7\\u09c8\\u09d7\\u09df-\\u09e0\\u0a01-\\u0a03\\u0a3c\\u0a3e-\\u0a42\\u0a47\\u0a48\\u0a4b-\\u0a4d\\u0a51\\u0a66-\\u0a71\\u0a75\\u0a81-\\u0a83\\u0abc\\u0abe-\\u0ac5\\u0ac7-\\u0ac9\\u0acb-\\u0acd\\u0ae2-\\u0ae3\\u0ae6-\\u0aef\\u0b01-\\u0b03\\u0b3c\\u0b3e-\\u0b44\\u0b47\\u0b48\\u0b4b-\\u0b4d\\u0b56\\u0b57\\u0b5f-\\u0b60\\u0b66-\\u0b6f\\u0b82\\u0bbe-\\u0bc2\\u0bc6-\\u0bc8\\u0bca-\\u0bcd\\u0bd7\\u0be6-\\u0bef\\u0c01-\\u0c03\\u0c46-\\u0c48\\u0c4a-\\u0c4d\\u0c55\\u0c56\\u0c62-\\u0c63\\u0c66-\\u0c6f\\u0c82\\u0c83\\u0cbc\\u0cbe-\\u0cc4\\u0cc6-\\u0cc8\\u0cca-\\u0ccd\\u0cd5\\u0cd6\\u0ce2-\\u0ce3\\u0ce6-\\u0cef\\u0d02\\u0d03\\u0d46-\\u0d48\\u0d57\\u0d62-\\u0d63\\u0d66-\\u0d6f\\u0d82\\u0d83\\u0dca\\u0dcf-\\u0dd4\\u0dd6\\u0dd8-\\u0ddf\\u0df2\\u0df3\\u0e34-\\u0e3a\\u0e40-\\u0e45\\u0e50-\\u0e59\\u0eb4-\\u0eb9\\u0ec8-\\u0ecd\\u0ed0-\\u0ed9\\u0f18\\u0f19\\u0f20-\\u0f29\\u0f35\\u0f37\\u0f39\\u0f41-\\u0f47\\u0f71-\\u0f84\\u0f86-\\u0f87\\u0f8d-\\u0f97\\u0f99-\\u0fbc\\u0fc6\\u1000-\\u1029\\u1040-\\u1049\\u1067-\\u106d\\u1071-\\u1074\\u1082-\\u108d\\u108f-\\u109d\\u135d-\\u135f\\u170e-\\u1710\\u1720-\\u1730\\u1740-\\u1750\\u1772\\u1773\\u1780-\\u17b2\\u17dd\\u17e0-\\u17e9\\u180b-\\u180d\\u1810-\\u1819\\u1920-\\u192b\\u1930-\\u193b\\u1951-\\u196d\\u19b0-\\u19c0\\u19c8-\\u19c9\\u19d0-\\u19d9\\u1a00-\\u1a15\\u1a20-\\u1a53\\u1a60-\\u1a7c\\u1a7f-\\u1a89\\u1a90-\\u1a99\\u1b46-\\u1b4b\\u1b50-\\u1b59\\u1b6b-\\u1b73\\u1bb0-\\u1bb9\\u1be6-\\u1bf3\\u1c00-\\u1c22\\u1c40-\\u1c49\\u1c5b-\\u1c7d\\u1cd0-\\u1cd2\\u1d00-\\u1dbe\\u1e01-\\u1f15\\u200c\\u200d\\u203f\\u2040\\u2054\\u20d0-\\u20dc\\u20e1\\u20e5-\\u20f0\\u2d81-\\u2d96\\u2de0-\\u2dff\\u3021-\\u3028\\u3099\\u309a\\ua640-\\ua66d\\ua674-\\ua67d\\ua69f\\ua6f0-\\ua6f1\\ua7f8-\\ua800\\ua806\\ua80b\\ua823-\\ua827\\ua880-\\ua881\\ua8b4-\\ua8c4\\ua8d0-\\ua8d9\\ua8f3-\\ua8f7\\ua900-\\ua909\\ua926-\\ua92d\\ua930-\\ua945\\ua980-\\ua983\\ua9b3-\\ua9c0\\uaa00-\\uaa27\\uaa40-\\uaa41\\uaa4c-\\uaa4d\\uaa50-\\uaa59\\uaa7b\\uaae0-\\uaae9\\uaaf2-\\uaaf3\\uabc0-\\uabe1\\uabec\\uabed\\uabf0-\\uabf9\\ufb20-\\ufb28\\ufe00-\\ufe0f\\ufe20-\\ufe26\\ufe33\\ufe34\\ufe4d-\\ufe4f\\uff10-\\uff19\\uff3f";var identifierStart="(?:\\\\u[0-9a-fA-F]{4}|["+baseASCIIidentifierStartChars+nonASCIIidentifierStartChars+"])";var identifierChars="(?:\\\\u[0-9a-fA-F]{4}|["+baseASCIIidentifierChars+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"])*";exports.identifier=new RegExp(identifierStart+identifierChars,"g");exports.identifierStart=new RegExp(identifierStart);exports.identifierMatch=new RegExp("(?:\\\\u[0-9a-fA-F]{4}|["+baseASCIIidentifierChars+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"])+");var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;exports.newline=/[\n\r\u2028\u2029]/;exports.lineBreak=new RegExp("\r\n|"+exports.newline.source);exports.allLineBreaks=new RegExp(exports.lineBreak.source,"g")},{}],136:[function(require,module,exports){"use strict";var Output=require("../core/output").Output;var Token=require("../core/token").Token;var acorn=require("./acorn");var Options=require("./options").Options;var Tokenizer=require("./tokenizer").Tokenizer;var line_starters=require("./tokenizer").line_starters;var positionable_operators=require("./tokenizer").positionable_operators;var TOKEN=require("./tokenizer").TOKEN;function in_array(what,arr){return arr.indexOf(what)!==-1}function ltrim(s){return s.replace(/^\s+/g,"")}function generateMapFromStrings(list){var result={};for(var x=0;xnext_indent_level){next_indent_level=flags_base.line_indent_level}}var next_flags={mode:mode,parent:flags_base,last_token:flags_base?flags_base.last_token:new Token(TOKEN.START_BLOCK,""),last_word:flags_base?flags_base.last_word:"",declaration_statement:false,declaration_assignment:false,multiline_frame:false,inline_frame:false,if_block:false,else_block:false,do_block:false,do_while:false,import_block:false,in_case_statement:false,in_case:false,case_body:false,indentation_level:next_indent_level,alignment:0,line_indent_level:flags_base?flags_base.line_indent_level:next_indent_level,start_line_index:this._output.get_line_number(),ternary_depth:0};return next_flags};Beautifier.prototype._reset=function(source_text){var baseIndentString=source_text.match(/^[\t ]*/)[0];this._last_last_text="";this._output=new Output(this._options,baseIndentString);this._output.raw=this._options.test_output_raw;this._flag_store=[];this.set_mode(MODE.BlockStatement);var tokenizer=new Tokenizer(source_text,this._options);this._tokens=tokenizer.tokenize();return source_text};Beautifier.prototype.beautify=function(){if(this._options.disabled){return this._source_text}var sweet_code;var source_text=this._reset(this._source_text);var eol=this._options.eol;if(this._options.eol==="auto"){eol="\n";if(source_text&&acorn.lineBreak.test(source_text||"")){eol=source_text.match(acorn.lineBreak)[0]}}var current_token=this._tokens.next();while(current_token){this.handle_token(current_token);this._last_last_text=this._flags.last_token.text;this._flags.last_token=current_token;current_token=this._tokens.next()}sweet_code=this._output.get_code(eol);return sweet_code};Beautifier.prototype.handle_token=function(current_token,preserve_statement_flags){if(current_token.type===TOKEN.START_EXPR){this.handle_start_expr(current_token)}else if(current_token.type===TOKEN.END_EXPR){this.handle_end_expr(current_token)}else if(current_token.type===TOKEN.START_BLOCK){this.handle_start_block(current_token)}else if(current_token.type===TOKEN.END_BLOCK){this.handle_end_block(current_token)}else if(current_token.type===TOKEN.WORD){this.handle_word(current_token)}else if(current_token.type===TOKEN.RESERVED){this.handle_word(current_token)}else if(current_token.type===TOKEN.SEMICOLON){this.handle_semicolon(current_token)}else if(current_token.type===TOKEN.STRING){this.handle_string(current_token)}else if(current_token.type===TOKEN.EQUALS){this.handle_equals(current_token)}else if(current_token.type===TOKEN.OPERATOR){this.handle_operator(current_token)}else if(current_token.type===TOKEN.COMMA){this.handle_comma(current_token)}else if(current_token.type===TOKEN.BLOCK_COMMENT){this.handle_block_comment(current_token,preserve_statement_flags)}else if(current_token.type===TOKEN.COMMENT){this.handle_comment(current_token,preserve_statement_flags)}else if(current_token.type===TOKEN.DOT){this.handle_dot(current_token)}else if(current_token.type===TOKEN.EOF){this.handle_eof(current_token)}else if(current_token.type===TOKEN.UNKNOWN){this.handle_unknown(current_token,preserve_statement_flags)}else{this.handle_unknown(current_token,preserve_statement_flags)}};Beautifier.prototype.handle_whitespace_and_comments=function(current_token,preserve_statement_flags){var newlines=current_token.newlines;var keep_whitespace=this._options.keep_array_indentation&&is_array(this._flags.mode);if(current_token.comments_before){var comment_token=current_token.comments_before.next();while(comment_token){this.handle_whitespace_and_comments(comment_token,preserve_statement_flags);this.handle_token(comment_token,preserve_statement_flags);comment_token=current_token.comments_before.next()}}if(keep_whitespace){for(var i=0;i0,preserve_statement_flags)}}else{if(this._options.max_preserve_newlines&&newlines>this._options.max_preserve_newlines){newlines=this._options.max_preserve_newlines}if(this._options.preserve_newlines){if(newlines>1){this.print_newline(false,preserve_statement_flags);for(var j=1;j0&&(!this._flags.parent||this._flags.indentation_level>this._flags.parent.indentation_level)){this._flags.indentation_level-=1;this._output.set_indent(this._flags.indentation_level,this._flags.alignment)}};Beautifier.prototype.set_mode=function(mode){if(this._flags){this._flag_store.push(this._flags);this._previous_flags=this._flags}else{this._previous_flags=this.create_flags(null,mode)}this._flags=this.create_flags(this._previous_flags,mode);this._output.set_indent(this._flags.indentation_level,this._flags.alignment)};Beautifier.prototype.restore_mode=function(){if(this._flag_store.length>0){this._previous_flags=this._flags;this._flags=this._flag_store.pop();if(this._previous_flags.mode===MODE.Statement){remove_redundant_indentation(this._output,this._previous_flags)}this._output.set_indent(this._flags.indentation_level,this._flags.alignment)}};Beautifier.prototype.start_of_object_property=function(){return this._flags.parent.mode===MODE.ObjectLiteral&&this._flags.mode===MODE.Statement&&(this._flags.last_token.text===":"&&this._flags.ternary_depth===0||reserved_array(this._flags.last_token,["get","set"]))};Beautifier.prototype.start_of_statement=function(current_token){var start=false;start=start||reserved_array(this._flags.last_token,["var","let","const"])&¤t_token.type===TOKEN.WORD;start=start||reserved_word(this._flags.last_token,"do");start=start||!(this._flags.parent.mode===MODE.ObjectLiteral&&this._flags.mode===MODE.Statement)&&reserved_array(this._flags.last_token,newline_restricted_tokens)&&!current_token.newlines;start=start||reserved_word(this._flags.last_token,"else")&&!(reserved_word(current_token,"if")&&!current_token.comments_before);start=start||this._flags.last_token.type===TOKEN.END_EXPR&&(this._previous_flags.mode===MODE.ForInitializer||this._previous_flags.mode===MODE.Conditional);start=start||this._flags.last_token.type===TOKEN.WORD&&this._flags.mode===MODE.BlockStatement&&!this._flags.in_case&&!(current_token.text==="--"||current_token.text==="++")&&this._last_last_text!=="function"&¤t_token.type!==TOKEN.WORD&¤t_token.type!==TOKEN.RESERVED;start=start||this._flags.mode===MODE.ObjectLiteral&&(this._flags.last_token.text===":"&&this._flags.ternary_depth===0||reserved_array(this._flags.last_token,["get","set"]));if(start){this.set_mode(MODE.Statement);this.indent();this.handle_whitespace_and_comments(current_token,true);if(!this.start_of_object_property()){this.allow_wrap_or_preserved_newline(current_token,reserved_array(current_token,["do","for","if","while"]))}return true}return false};Beautifier.prototype.handle_start_expr=function(current_token){if(!this.start_of_statement(current_token)){this.handle_whitespace_and_comments(current_token)}var next_mode=MODE.Expression;if(current_token.text==="["){if(this._flags.last_token.type===TOKEN.WORD||this._flags.last_token.text===")"){if(reserved_array(this._flags.last_token,line_starters)){this._output.space_before_token=true}this.print_token(current_token);this.set_mode(next_mode);this.indent();if(this._options.space_in_paren){this._output.space_before_token=true}return}next_mode=MODE.ArrayLiteral;if(is_array(this._flags.mode)){if(this._flags.last_token.text==="["||this._flags.last_token.text===","&&(this._last_last_text==="]"||this._last_last_text==="}")){if(!this._options.keep_array_indentation){this.print_newline()}}}if(!in_array(this._flags.last_token.type,[TOKEN.START_EXPR,TOKEN.END_EXPR,TOKEN.WORD,TOKEN.OPERATOR,TOKEN.DOT])){this._output.space_before_token=true}}else{if(this._flags.last_token.type===TOKEN.RESERVED){if(this._flags.last_token.text==="for"){this._output.space_before_token=this._options.space_before_conditional;next_mode=MODE.ForInitializer}else if(in_array(this._flags.last_token.text,["if","while","switch"])){this._output.space_before_token=this._options.space_before_conditional;next_mode=MODE.Conditional}else if(in_array(this._flags.last_word,["await","async"])){this._output.space_before_token=true}else if(this._flags.last_token.text==="import"&¤t_token.whitespace_before===""){this._output.space_before_token=false}else if(in_array(this._flags.last_token.text,line_starters)||this._flags.last_token.text==="catch"){this._output.space_before_token=true}}else if(this._flags.last_token.type===TOKEN.EQUALS||this._flags.last_token.type===TOKEN.OPERATOR){if(!this.start_of_object_property()){this.allow_wrap_or_preserved_newline(current_token)}}else if(this._flags.last_token.type===TOKEN.WORD){this._output.space_before_token=false;var peek_back_two=this._tokens.peek(-3);if(this._options.space_after_named_function&&peek_back_two){var peek_back_three=this._tokens.peek(-4);if(reserved_array(peek_back_two,["async","function"])||peek_back_two.text==="*"&&reserved_array(peek_back_three,["async","function"])){this._output.space_before_token=true}else if(this._flags.mode===MODE.ObjectLiteral){if(peek_back_two.text==="{"||peek_back_two.text===","||peek_back_two.text==="*"&&(peek_back_three.text==="{"||peek_back_three.text===",")){this._output.space_before_token=true}}}}else{this.allow_wrap_or_preserved_newline(current_token)}if(this._flags.last_token.type===TOKEN.RESERVED&&(this._flags.last_word==="function"||this._flags.last_word==="typeof")||this._flags.last_token.text==="*"&&(in_array(this._last_last_text,["function","yield"])||this._flags.mode===MODE.ObjectLiteral&&in_array(this._last_last_text,["{",","]))){this._output.space_before_token=this._options.space_after_anon_function}}if(this._flags.last_token.text===";"||this._flags.last_token.type===TOKEN.START_BLOCK){this.print_newline()}else if(this._flags.last_token.type===TOKEN.END_EXPR||this._flags.last_token.type===TOKEN.START_EXPR||this._flags.last_token.type===TOKEN.END_BLOCK||this._flags.last_token.text==="."||this._flags.last_token.type===TOKEN.COMMA){this.allow_wrap_or_preserved_newline(current_token,current_token.newlines)}this.print_token(current_token);this.set_mode(next_mode);if(this._options.space_in_paren){this._output.space_before_token=true}this.indent()};Beautifier.prototype.handle_end_expr=function(current_token){while(this._flags.mode===MODE.Statement){this.restore_mode()}this.handle_whitespace_and_comments(current_token);if(this._flags.multiline_frame){this.allow_wrap_or_preserved_newline(current_token,current_token.text==="]"&&is_array(this._flags.mode)&&!this._options.keep_array_indentation)}if(this._options.space_in_paren){if(this._flags.last_token.type===TOKEN.START_EXPR&&!this._options.space_in_empty_paren){this._output.trim();this._output.space_before_token=false}else{this._output.space_before_token=true}}this.deindent();this.print_token(current_token);this.restore_mode();remove_redundant_indentation(this._output,this._previous_flags);if(this._flags.do_while&&this._previous_flags.mode===MODE.Conditional){this._previous_flags.mode=MODE.Expression;this._flags.do_block=false;this._flags.do_while=false}};Beautifier.prototype.handle_start_block=function(current_token){this.handle_whitespace_and_comments(current_token);var next_token=this._tokens.peek();var second_token=this._tokens.peek(1);if(this._flags.last_word==="switch"&&this._flags.last_token.type===TOKEN.END_EXPR){this.set_mode(MODE.BlockStatement);this._flags.in_case_statement=true}else if(this._flags.case_body){this.set_mode(MODE.BlockStatement)}else if(second_token&&(in_array(second_token.text,[":",","])&&in_array(next_token.type,[TOKEN.STRING,TOKEN.WORD,TOKEN.RESERVED])||in_array(next_token.text,["get","set","..."])&&in_array(second_token.type,[TOKEN.WORD,TOKEN.RESERVED]))){if(!in_array(this._last_last_text,["class","interface"])){this.set_mode(MODE.ObjectLiteral)}else{this.set_mode(MODE.BlockStatement)}}else if(this._flags.last_token.type===TOKEN.OPERATOR&&this._flags.last_token.text==="=>"){this.set_mode(MODE.BlockStatement)}else if(in_array(this._flags.last_token.type,[TOKEN.EQUALS,TOKEN.START_EXPR,TOKEN.COMMA,TOKEN.OPERATOR])||reserved_array(this._flags.last_token,["return","throw","import","default"])){this.set_mode(MODE.ObjectLiteral)}else{this.set_mode(MODE.BlockStatement)}var empty_braces=!next_token.comments_before&&next_token.text==="}";var empty_anonymous_function=empty_braces&&this._flags.last_word==="function"&&this._flags.last_token.type===TOKEN.END_EXPR;if(this._options.brace_preserve_inline){var index=0;var check_token=null;this._flags.inline_frame=true;do{index+=1;check_token=this._tokens.peek(index-1);if(check_token.newlines){this._flags.inline_frame=false;break}}while(check_token.type!==TOKEN.EOF&&!(check_token.type===TOKEN.END_BLOCK&&check_token.opened===current_token))}if((this._options.brace_style==="expand"||this._options.brace_style==="none"&¤t_token.newlines)&&!this._flags.inline_frame){if(this._flags.last_token.type!==TOKEN.OPERATOR&&(empty_anonymous_function||this._flags.last_token.type===TOKEN.EQUALS||reserved_array(this._flags.last_token,special_words)&&this._flags.last_token.text!=="else")){this._output.space_before_token=true}else{this.print_newline(false,true)}}else{if(is_array(this._previous_flags.mode)&&(this._flags.last_token.type===TOKEN.START_EXPR||this._flags.last_token.type===TOKEN.COMMA)){if(this._flags.last_token.type===TOKEN.COMMA||this._options.space_in_paren){this._output.space_before_token=true}if(this._flags.last_token.type===TOKEN.COMMA||this._flags.last_token.type===TOKEN.START_EXPR&&this._flags.inline_frame){this.allow_wrap_or_preserved_newline(current_token);this._previous_flags.multiline_frame=this._previous_flags.multiline_frame||this._flags.multiline_frame;this._flags.multiline_frame=false}}if(this._flags.last_token.type!==TOKEN.OPERATOR&&this._flags.last_token.type!==TOKEN.START_EXPR){if(this._flags.last_token.type===TOKEN.START_BLOCK&&!this._flags.inline_frame){this.print_newline()}else{this._output.space_before_token=true}}}this.print_token(current_token);this.indent();if(!empty_braces&&!(this._options.brace_preserve_inline&&this._flags.inline_frame)){this.print_newline()}};Beautifier.prototype.handle_end_block=function(current_token){this.handle_whitespace_and_comments(current_token);while(this._flags.mode===MODE.Statement){this.restore_mode()}var empty_braces=this._flags.last_token.type===TOKEN.START_BLOCK;if(this._flags.inline_frame&&!empty_braces){this._output.space_before_token=true}else if(this._options.brace_style==="expand"){if(!empty_braces){this.print_newline()}}else{if(!empty_braces){if(is_array(this._flags.mode)&&this._options.keep_array_indentation){this._options.keep_array_indentation=false;this.print_newline();this._options.keep_array_indentation=true}else{this.print_newline()}}}this.restore_mode();this.print_token(current_token)};Beautifier.prototype.handle_word=function(current_token){if(current_token.type===TOKEN.RESERVED){if(in_array(current_token.text,["set","get"])&&this._flags.mode!==MODE.ObjectLiteral){current_token.type=TOKEN.WORD}else if(current_token.text==="import"&&this._tokens.peek().text==="("){current_token.type=TOKEN.WORD}else if(in_array(current_token.text,["as","from"])&&!this._flags.import_block){current_token.type=TOKEN.WORD}else if(this._flags.mode===MODE.ObjectLiteral){var next_token=this._tokens.peek();if(next_token.text===":"){current_token.type=TOKEN.WORD}}}if(this.start_of_statement(current_token)){if(reserved_array(this._flags.last_token,["var","let","const"])&¤t_token.type===TOKEN.WORD){this._flags.declaration_statement=true}}else if(current_token.newlines&&!is_expression(this._flags.mode)&&(this._flags.last_token.type!==TOKEN.OPERATOR||(this._flags.last_token.text==="--"||this._flags.last_token.text==="++"))&&this._flags.last_token.type!==TOKEN.EQUALS&&(this._options.preserve_newlines||!reserved_array(this._flags.last_token,["var","let","const","set","get"]))){this.handle_whitespace_and_comments(current_token);this.print_newline()}else{this.handle_whitespace_and_comments(current_token)}if(this._flags.do_block&&!this._flags.do_while){if(reserved_word(current_token,"while")){this._output.space_before_token=true;this.print_token(current_token);this._output.space_before_token=true;this._flags.do_while=true;return}else{this.print_newline();this._flags.do_block=false}}if(this._flags.if_block){if(!this._flags.else_block&&reserved_word(current_token,"else")){this._flags.else_block=true}else{while(this._flags.mode===MODE.Statement){this.restore_mode()}this._flags.if_block=false;this._flags.else_block=false}}if(this._flags.in_case_statement&&reserved_array(current_token,["case","default"])){this.print_newline();if(this._flags.last_token.type!==TOKEN.END_BLOCK&&(this._flags.case_body||this._options.jslint_happy)){this.deindent()}this._flags.case_body=false;this.print_token(current_token);this._flags.in_case=true;return}if(this._flags.last_token.type===TOKEN.COMMA||this._flags.last_token.type===TOKEN.START_EXPR||this._flags.last_token.type===TOKEN.EQUALS||this._flags.last_token.type===TOKEN.OPERATOR){if(!this.start_of_object_property()){this.allow_wrap_or_preserved_newline(current_token)}}if(reserved_word(current_token,"function")){if(in_array(this._flags.last_token.text,["}",";"])||this._output.just_added_newline()&&!(in_array(this._flags.last_token.text,["(","[","{",":","=",","])||this._flags.last_token.type===TOKEN.OPERATOR)){if(!this._output.just_added_blankline()&&!current_token.comments_before){this.print_newline();this.print_newline(true)}}if(this._flags.last_token.type===TOKEN.RESERVED||this._flags.last_token.type===TOKEN.WORD){if(reserved_array(this._flags.last_token,["get","set","new","export"])||reserved_array(this._flags.last_token,newline_restricted_tokens)){this._output.space_before_token=true}else if(reserved_word(this._flags.last_token,"default")&&this._last_last_text==="export"){this._output.space_before_token=true}else if(this._flags.last_token.text==="declare"){this._output.space_before_token=true}else{this.print_newline()}}else if(this._flags.last_token.type===TOKEN.OPERATOR||this._flags.last_token.text==="="){this._output.space_before_token=true}else if(!this._flags.multiline_frame&&(is_expression(this._flags.mode)||is_array(this._flags.mode))){}else{this.print_newline()}this.print_token(current_token);this._flags.last_word=current_token.text;return}var prefix="NONE";if(this._flags.last_token.type===TOKEN.END_BLOCK){if(this._previous_flags.inline_frame){prefix="SPACE"}else if(!reserved_array(current_token,["else","catch","finally","from"])){prefix="NEWLINE"}else{if(this._options.brace_style==="expand"||this._options.brace_style==="end-expand"||this._options.brace_style==="none"&¤t_token.newlines){prefix="NEWLINE"}else{prefix="SPACE";this._output.space_before_token=true}}}else if(this._flags.last_token.type===TOKEN.SEMICOLON&&this._flags.mode===MODE.BlockStatement){prefix="NEWLINE"}else if(this._flags.last_token.type===TOKEN.SEMICOLON&&is_expression(this._flags.mode)){prefix="SPACE"}else if(this._flags.last_token.type===TOKEN.STRING){prefix="NEWLINE"}else if(this._flags.last_token.type===TOKEN.RESERVED||this._flags.last_token.type===TOKEN.WORD||this._flags.last_token.text==="*"&&(in_array(this._last_last_text,["function","yield"])||this._flags.mode===MODE.ObjectLiteral&&in_array(this._last_last_text,["{",","]))){prefix="SPACE"}else if(this._flags.last_token.type===TOKEN.START_BLOCK){if(this._flags.inline_frame){prefix="SPACE"}else{prefix="NEWLINE"}}else if(this._flags.last_token.type===TOKEN.END_EXPR){this._output.space_before_token=true;prefix="NEWLINE"}if(reserved_array(current_token,line_starters)&&this._flags.last_token.text!==")"){if(this._flags.inline_frame||this._flags.last_token.text==="else"||this._flags.last_token.text==="export"){prefix="SPACE"}else{prefix="NEWLINE"}}if(reserved_array(current_token,["else","catch","finally"])){if((!(this._flags.last_token.type===TOKEN.END_BLOCK&&this._previous_flags.mode===MODE.BlockStatement)||this._options.brace_style==="expand"||this._options.brace_style==="end-expand"||this._options.brace_style==="none"&¤t_token.newlines)&&!this._flags.inline_frame){this.print_newline()}else{this._output.trim(true);var line=this._output.current_line;if(line.last()!=="}"){this.print_newline()}this._output.space_before_token=true}}else if(prefix==="NEWLINE"){if(reserved_array(this._flags.last_token,special_words)){this._output.space_before_token=true}else if(this._flags.last_token.text==="declare"&&reserved_array(current_token,["var","let","const"])){this._output.space_before_token=true}else if(this._flags.last_token.type!==TOKEN.END_EXPR){if((this._flags.last_token.type!==TOKEN.START_EXPR||!reserved_array(current_token,["var","let","const"]))&&this._flags.last_token.text!==":"){if(reserved_word(current_token,"if")&&reserved_word(current_token.previous,"else")){this._output.space_before_token=true}else{this.print_newline()}}}else if(reserved_array(current_token,line_starters)&&this._flags.last_token.text!==")"){this.print_newline()}}else if(this._flags.multiline_frame&&is_array(this._flags.mode)&&this._flags.last_token.text===","&&this._last_last_text==="}"){this.print_newline()}else if(prefix==="SPACE"){this._output.space_before_token=true}if(current_token.previous&&(current_token.previous.type===TOKEN.WORD||current_token.previous.type===TOKEN.RESERVED)){this._output.space_before_token=true}this.print_token(current_token);this._flags.last_word=current_token.text;if(current_token.type===TOKEN.RESERVED){if(current_token.text==="do"){this._flags.do_block=true}else if(current_token.text==="if"){this._flags.if_block=true}else if(current_token.text==="import"){this._flags.import_block=true}else if(this._flags.import_block&&reserved_word(current_token,"from")){this._flags.import_block=false}}};Beautifier.prototype.handle_semicolon=function(current_token){if(this.start_of_statement(current_token)){this._output.space_before_token=false}else{this.handle_whitespace_and_comments(current_token)}var next_token=this._tokens.peek();while(this._flags.mode===MODE.Statement&&!(this._flags.if_block&&reserved_word(next_token,"else"))&&!this._flags.do_block){this.restore_mode()}if(this._flags.import_block){this._flags.import_block=false}this.print_token(current_token)};Beautifier.prototype.handle_string=function(current_token){if(current_token.text.startsWith("`")&¤t_token.newlines===0&¤t_token.whitespace_before===""&&(current_token.previous.text===")"||this._flags.last_token.type===TOKEN.WORD)){}else if(this.start_of_statement(current_token)){this._output.space_before_token=true}else{this.handle_whitespace_and_comments(current_token);if(this._flags.last_token.type===TOKEN.RESERVED||this._flags.last_token.type===TOKEN.WORD||this._flags.inline_frame){this._output.space_before_token=true}else if(this._flags.last_token.type===TOKEN.COMMA||this._flags.last_token.type===TOKEN.START_EXPR||this._flags.last_token.type===TOKEN.EQUALS||this._flags.last_token.type===TOKEN.OPERATOR){if(!this.start_of_object_property()){this.allow_wrap_or_preserved_newline(current_token)}}else if(current_token.text.startsWith("`")&&this._flags.last_token.type===TOKEN.END_EXPR&&(current_token.previous.text==="]"||current_token.previous.text===")")&¤t_token.newlines===0){this._output.space_before_token=true}else{this.print_newline()}}this.print_token(current_token)};Beautifier.prototype.handle_equals=function(current_token){if(this.start_of_statement(current_token)){}else{this.handle_whitespace_and_comments(current_token)}if(this._flags.declaration_statement){this._flags.declaration_assignment=true}this._output.space_before_token=true;this.print_token(current_token);this._output.space_before_token=true};Beautifier.prototype.handle_comma=function(current_token){this.handle_whitespace_and_comments(current_token,true);this.print_token(current_token);this._output.space_before_token=true;if(this._flags.declaration_statement){if(is_expression(this._flags.parent.mode)){this._flags.declaration_assignment=false}if(this._flags.declaration_assignment){this._flags.declaration_assignment=false;this.print_newline(false,true)}else if(this._options.comma_first){this.allow_wrap_or_preserved_newline(current_token)}}else if(this._flags.mode===MODE.ObjectLiteral||this._flags.mode===MODE.Statement&&this._flags.parent.mode===MODE.ObjectLiteral){if(this._flags.mode===MODE.Statement){this.restore_mode()}if(!this._flags.inline_frame){this.print_newline()}}else if(this._options.comma_first){this.allow_wrap_or_preserved_newline(current_token)}};Beautifier.prototype.handle_operator=function(current_token){var isGeneratorAsterisk=current_token.text==="*"&&(reserved_array(this._flags.last_token,["function","yield"])||in_array(this._flags.last_token.type,[TOKEN.START_BLOCK,TOKEN.COMMA,TOKEN.END_BLOCK,TOKEN.SEMICOLON]));var isUnary=in_array(current_token.text,["-","+"])&&(in_array(this._flags.last_token.type,[TOKEN.START_BLOCK,TOKEN.START_EXPR,TOKEN.EQUALS,TOKEN.OPERATOR])||in_array(this._flags.last_token.text,line_starters)||this._flags.last_token.text===",");if(this.start_of_statement(current_token)){}else{var preserve_statement_flags=!isGeneratorAsterisk;this.handle_whitespace_and_comments(current_token,preserve_statement_flags)}if(reserved_array(this._flags.last_token,special_words)){this._output.space_before_token=true;this.print_token(current_token);return}if(current_token.text==="*"&&this._flags.last_token.type===TOKEN.DOT){this.print_token(current_token);return}if(current_token.text==="::"){this.print_token(current_token);return}if(this._flags.last_token.type===TOKEN.OPERATOR&&in_array(this._options.operator_position,OPERATOR_POSITION_BEFORE_OR_PRESERVE)){this.allow_wrap_or_preserved_newline(current_token)}if(current_token.text===":"&&this._flags.in_case){this.print_token(current_token);this._flags.in_case=false;this._flags.case_body=true;if(this._tokens.peek().type!==TOKEN.START_BLOCK){this.indent();this.print_newline()}else{this._output.space_before_token=true}return}var space_before=true;var space_after=true;var in_ternary=false;if(current_token.text===":"){if(this._flags.ternary_depth===0){space_before=false}else{this._flags.ternary_depth-=1;in_ternary=true}}else if(current_token.text==="?"){this._flags.ternary_depth+=1}if(!isUnary&&!isGeneratorAsterisk&&this._options.preserve_newlines&&in_array(current_token.text,positionable_operators)){var isColon=current_token.text===":";var isTernaryColon=isColon&&in_ternary;var isOtherColon=isColon&&!in_ternary;switch(this._options.operator_position){case OPERATOR_POSITION.before_newline:this._output.space_before_token=!isOtherColon;this.print_token(current_token);if(!isColon||isTernaryColon){this.allow_wrap_or_preserved_newline(current_token)}this._output.space_before_token=true;return;case OPERATOR_POSITION.after_newline:this._output.space_before_token=true;if(!isColon||isTernaryColon){if(this._tokens.peek().newlines){this.print_newline(false,true)}else{this.allow_wrap_or_preserved_newline(current_token)}}else{this._output.space_before_token=false}this.print_token(current_token);this._output.space_before_token=true;return;case OPERATOR_POSITION.preserve_newline:if(!isOtherColon){this.allow_wrap_or_preserved_newline(current_token)}space_before=!(this._output.just_added_newline()||isOtherColon);this._output.space_before_token=space_before;this.print_token(current_token);this._output.space_before_token=true;return}}if(isGeneratorAsterisk){this.allow_wrap_or_preserved_newline(current_token);space_before=false;var next_token=this._tokens.peek();space_after=next_token&&in_array(next_token.type,[TOKEN.WORD,TOKEN.RESERVED])}else if(current_token.text==="..."){this.allow_wrap_or_preserved_newline(current_token);space_before=this._flags.last_token.type===TOKEN.START_BLOCK;space_after=false}else if(in_array(current_token.text,["--","++","!","~"])||isUnary){if(this._flags.last_token.type===TOKEN.COMMA||this._flags.last_token.type===TOKEN.START_EXPR){this.allow_wrap_or_preserved_newline(current_token)}space_before=false;space_after=false;if(current_token.newlines&&(current_token.text==="--"||current_token.text==="++")){this.print_newline(false,true)}if(this._flags.last_token.text===";"&&is_expression(this._flags.mode)){space_before=true}if(this._flags.last_token.type===TOKEN.RESERVED){space_before=true}else if(this._flags.last_token.type===TOKEN.END_EXPR){space_before=!(this._flags.last_token.text==="]"&&(current_token.text==="--"||current_token.text==="++"))}else if(this._flags.last_token.type===TOKEN.OPERATOR){space_before=in_array(current_token.text,["--","-","++","+"])&&in_array(this._flags.last_token.text,["--","-","++","+"]);if(in_array(current_token.text,["+","-"])&&in_array(this._flags.last_token.text,["--","++"])){space_after=true}}if((this._flags.mode===MODE.BlockStatement&&!this._flags.inline_frame||this._flags.mode===MODE.Statement)&&(this._flags.last_token.text==="{"||this._flags.last_token.text===";")){this.print_newline()}}this._output.space_before_token=this._output.space_before_token||space_before;this.print_token(current_token);this._output.space_before_token=space_after};Beautifier.prototype.handle_block_comment=function(current_token,preserve_statement_flags){if(this._output.raw){this._output.add_raw_token(current_token);if(current_token.directives&¤t_token.directives.preserve==="end"){this._output.raw=this._options.test_output_raw}return}if(current_token.directives){this.print_newline(false,preserve_statement_flags);this.print_token(current_token);if(current_token.directives.preserve==="start"){this._output.raw=true}this.print_newline(false,true);return}if(!acorn.newline.test(current_token.text)&&!current_token.newlines){this._output.space_before_token=true;this.print_token(current_token);this._output.space_before_token=true;return}else{this.print_block_commment(current_token,preserve_statement_flags)}};Beautifier.prototype.print_block_commment=function(current_token,preserve_statement_flags){var lines=split_linebreaks(current_token.text);var j;var javadoc=false;var starless=false;var lastIndent=current_token.whitespace_before;var lastIndentLength=lastIndent.length;this.print_newline(false,preserve_statement_flags);this.print_token_line_indentation(current_token);this._output.add_token(lines[0]);this.print_newline(false,preserve_statement_flags);if(lines.length>1){lines=lines.slice(1);javadoc=all_lines_start_with(lines,"*");starless=each_line_matches_indent(lines,lastIndent);if(javadoc){this._flags.alignment=1}for(j=0;j>> === !== "+"<< && >= ** != == <= >> || ?? |> "+"< / - + > : & % ? ^ | *").split(" ");var punct=">>>= "+"... >>= <<= === >>> !== **= "+"=> ^= :: /= << <= == && -= >= >> != -- += ** || ?? ++ %= &= *= |= |> "+"= ! ? > < : / ^ - + * & % ~ |";punct=punct.replace(/[-[\]{}()*+?.,\\^$|#]/g,"\\$&");punct="\\?\\.(?!\\d) "+punct;punct=punct.replace(/ /g,"|");var punct_pattern=new RegExp(punct);var line_starters="continue,try,throw,return,var,let,const,if,switch,case,default,for,while,break,function,import,export".split(",");var reserved_words=line_starters.concat(["do","in","of","else","get","set","new","catch","finally","typeof","yield","async","await","from","as"]);var reserved_word_pattern=new RegExp("^(?:"+reserved_words.join("|")+")$");var in_html_comment;var Tokenizer=function(input_string,options){BaseTokenizer.call(this,input_string,options);this._patterns.whitespace=this._patterns.whitespace.matching(/\u00A0\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff/.source,/\u2028\u2029/.source);var pattern_reader=new Pattern(this._input);var templatable=new TemplatablePattern(this._input).read_options(this._options);this.__patterns={template:templatable,identifier:templatable.starting_with(acorn.identifier).matching(acorn.identifierMatch),number:pattern_reader.matching(number_pattern),punct:pattern_reader.matching(punct_pattern),comment:pattern_reader.starting_with(/\/\//).until(/[\n\r\u2028\u2029]/),block_comment:pattern_reader.starting_with(/\/\*/).until_after(/\*\//),html_comment_start:pattern_reader.matching(//),include:pattern_reader.starting_with(/#include/).until_after(acorn.lineBreak),shebang:pattern_reader.starting_with(/#!/).until_after(acorn.lineBreak),xml:pattern_reader.matching(/[\s\S]*?<(\/?)([-a-zA-Z:0-9_.]+|{[\s\S]+?}|!\[CDATA\[[\s\S]*?\]\]|)(\s+{[\s\S]+?}|\s+[-a-zA-Z:0-9_.]+|\s+[-a-zA-Z:0-9_.]+\s*=\s*('[^']*'|"[^"]*"|{[\s\S]+?}))*\s*(\/?)\s*>/),single_quote:templatable.until(/['\\\n\r\u2028\u2029]/),double_quote:templatable.until(/["\\\n\r\u2028\u2029]/),template_text:templatable.until(/[`\\$]/),template_expression:templatable.until(/[`}\\]/)}};Tokenizer.prototype=new BaseTokenizer;Tokenizer.prototype._is_comment=function(current_token){return current_token.type===TOKEN.COMMENT||current_token.type===TOKEN.BLOCK_COMMENT||current_token.type===TOKEN.UNKNOWN};Tokenizer.prototype._is_opening=function(current_token){return current_token.type===TOKEN.START_BLOCK||current_token.type===TOKEN.START_EXPR};Tokenizer.prototype._is_closing=function(current_token,open_token){return(current_token.type===TOKEN.END_BLOCK||current_token.type===TOKEN.END_EXPR)&&(open_token&&(current_token.text==="]"&&open_token.text==="["||current_token.text===")"&&open_token.text==="("||current_token.text==="}"&&open_token.text==="{"))};Tokenizer.prototype._reset=function(){in_html_comment=false};Tokenizer.prototype._get_next_token=function(previous_token,open_token){var token=null;this._readWhitespace();var c=this._input.peek();if(c===null){return this._create_token(TOKEN.EOF,"")}token=token||this._read_non_javascript(c);token=token||this._read_string(c);token=token||this._read_word(previous_token);token=token||this._read_singles(c);token=token||this._read_comment(c);token=token||this._read_regexp(c,previous_token);token=token||this._read_xml(c,previous_token);token=token||this._read_punctuation();token=token||this._create_token(TOKEN.UNKNOWN,this._input.next());return token};Tokenizer.prototype._read_word=function(previous_token){var resulting_string;resulting_string=this.__patterns.identifier.read();if(resulting_string!==""){resulting_string=resulting_string.replace(acorn.allLineBreaks,"\n");if(!(previous_token.type===TOKEN.DOT||previous_token.type===TOKEN.RESERVED&&(previous_token.text==="set"||previous_token.text==="get"))&&reserved_word_pattern.test(resulting_string)){if(resulting_string==="in"||resulting_string==="of"){return this._create_token(TOKEN.OPERATOR,resulting_string)}return this._create_token(TOKEN.RESERVED,resulting_string)}return this._create_token(TOKEN.WORD,resulting_string)}resulting_string=this.__patterns.number.read();if(resulting_string!==""){return this._create_token(TOKEN.WORD,resulting_string)}};Tokenizer.prototype._read_singles=function(c){var token=null;if(c==="("||c==="["){token=this._create_token(TOKEN.START_EXPR,c)}else if(c===")"||c==="]"){token=this._create_token(TOKEN.END_EXPR,c)}else if(c==="{"){token=this._create_token(TOKEN.START_BLOCK,c)}else if(c==="}"){token=this._create_token(TOKEN.END_BLOCK,c)}else if(c===";"){token=this._create_token(TOKEN.SEMICOLON,c)}else if(c==="."&&dot_pattern.test(this._input.peek(1))){token=this._create_token(TOKEN.DOT,c)}else if(c===","){token=this._create_token(TOKEN.COMMA,c)}if(token){this._input.next()}return token};Tokenizer.prototype._read_punctuation=function(){var resulting_string=this.__patterns.punct.read();if(resulting_string!==""){if(resulting_string==="="){return this._create_token(TOKEN.EQUALS,resulting_string)}else if(resulting_string==="?."){return this._create_token(TOKEN.DOT,resulting_string)}else{return this._create_token(TOKEN.OPERATOR,resulting_string)}}};Tokenizer.prototype._read_non_javascript=function(c){var resulting_string="";if(c==="#"){if(this._is_first_token()){resulting_string=this.__patterns.shebang.read();if(resulting_string){return this._create_token(TOKEN.UNKNOWN,resulting_string.trim()+"\n")}}resulting_string=this.__patterns.include.read();if(resulting_string){return this._create_token(TOKEN.UNKNOWN,resulting_string.trim()+"\n")}c=this._input.next();var sharp="#";if(this._input.hasNext()&&this._input.testChar(digit)){do{c=this._input.next();sharp+=c}while(this._input.hasNext()&&c!=="#"&&c!=="=");if(c==="#"){}else if(this._input.peek()==="["&&this._input.peek(1)==="]"){sharp+="[]";this._input.next();this._input.next()}else if(this._input.peek()==="{"&&this._input.peek(1)==="}"){sharp+="{}";this._input.next();this._input.next()}return this._create_token(TOKEN.WORD,sharp)}this._input.back()}else if(c==="<"&&this._is_first_token()){resulting_string=this.__patterns.html_comment_start.read();if(resulting_string){while(this._input.hasNext()&&!this._input.testChar(acorn.newline)){resulting_string+=this._input.next()}in_html_comment=true;return this._create_token(TOKEN.COMMENT,resulting_string)}}else if(in_html_comment&&c==="-"){resulting_string=this.__patterns.html_comment_end.read();if(resulting_string){in_html_comment=false;return this._create_token(TOKEN.COMMENT,resulting_string)}}return null};Tokenizer.prototype._read_comment=function(c){var token=null;if(c==="/"){var comment="";if(this._input.peek(1)==="*"){comment=this.__patterns.block_comment.read();var directives=directives_core.get_directives(comment);if(directives&&directives.ignore==="start"){comment+=directives_core.readIgnored(this._input)}comment=comment.replace(acorn.allLineBreaks,"\n");token=this._create_token(TOKEN.BLOCK_COMMENT,comment);token.directives=directives}else if(this._input.peek(1)==="/"){comment=this.__patterns.comment.read();token=this._create_token(TOKEN.COMMENT,comment)}}return token};Tokenizer.prototype._read_string=function(c){if(c==="`"||c==="'"||c==='"'){var resulting_string=this._input.next();this.has_char_escapes=false;if(c==="`"){resulting_string+=this._read_string_recursive("`",true,"${")}else{resulting_string+=this._read_string_recursive(c)}if(this.has_char_escapes&&this._options.unescape_strings){resulting_string=unescape_string(resulting_string)}if(this._input.peek()===c){resulting_string+=this._input.next()}resulting_string=resulting_string.replace(acorn.allLineBreaks,"\n");return this._create_token(TOKEN.STRING,resulting_string)}return null};Tokenizer.prototype._allow_regexp_or_xml=function(previous_token){return previous_token.type===TOKEN.RESERVED&&in_array(previous_token.text,["return","case","throw","else","do","typeof","yield"])||previous_token.type===TOKEN.END_EXPR&&previous_token.text===")"&&previous_token.opened.previous.type===TOKEN.RESERVED&&in_array(previous_token.opened.previous.text,["if","while","for"])||in_array(previous_token.type,[TOKEN.COMMENT,TOKEN.START_EXPR,TOKEN.START_BLOCK,TOKEN.START,TOKEN.END_BLOCK,TOKEN.OPERATOR,TOKEN.EQUALS,TOKEN.EOF,TOKEN.SEMICOLON,TOKEN.COMMA])};Tokenizer.prototype._read_regexp=function(c,previous_token){if(c==="/"&&this._allow_regexp_or_xml(previous_token)){var resulting_string=this._input.next();var esc=false;var in_char_class=false;while(this._input.hasNext()&&((esc||in_char_class||this._input.peek()!==c)&&!this._input.testChar(acorn.newline))){resulting_string+=this._input.peek();if(!esc){esc=this._input.peek()==="\\";if(this._input.peek()==="["){in_char_class=true}else if(this._input.peek()==="]"){in_char_class=false}}else{esc=false}this._input.next()}if(this._input.peek()===c){resulting_string+=this._input.next();resulting_string+=this._input.read(acorn.identifier)}return this._create_token(TOKEN.STRING,resulting_string)}return null};Tokenizer.prototype._read_xml=function(c,previous_token){if(this._options.e4x&&c==="<"&&this._allow_regexp_or_xml(previous_token)){var xmlStr="";var match=this.__patterns.xml.read_match();if(match){var rootTag=match[2].replace(/^{\s+/,"{").replace(/\s+}$/,"}");var isCurlyRoot=rootTag.indexOf("{")===0;var depth=0;while(match){var isEndTag=!!match[1];var tagName=match[2];var isSingletonTag=!!match[match.length-1]||tagName.slice(0,8)==="![CDATA[";if(!isSingletonTag&&(tagName===rootTag||isCurlyRoot&&tagName.replace(/^{\s+/,"{").replace(/\s+}$/,"}"))){if(isEndTag){--depth}else{++depth}}xmlStr+=match[0];if(depth<=0){break}match=this.__patterns.xml.read_match()}if(!match){xmlStr+=this._input.match(/[\s\S]*/g)[0]}xmlStr=xmlStr.replace(acorn.allLineBreaks,"\n");return this._create_token(TOKEN.STRING,xmlStr)}}return null};function unescape_string(s){var out="",escaped=0;var input_scan=new InputScanner(s);var matched=null;while(input_scan.hasNext()){matched=input_scan.match(/([\s]|[^\\]|\\\\)+/g);if(matched){out+=matched[0]}if(input_scan.peek()==="\\"){input_scan.next();if(input_scan.peek()==="x"){matched=input_scan.match(/x([0-9A-Fa-f]{2})/g)}else if(input_scan.peek()==="u"){matched=input_scan.match(/u([0-9A-Fa-f]{4})/g)}else{out+="\\";if(input_scan.hasNext()){out+=input_scan.next()}continue}if(!matched){return s}escaped=parseInt(matched[1],16);if(escaped>126&&escaped<=255&&matched[0].indexOf("x")===0){return s}else if(escaped>=0&&escaped<32){out+="\\"+matched[0];continue}else if(escaped===34||escaped===39||escaped===92){out+="\\"+String.fromCharCode(escaped)}else{out+=String.fromCharCode(escaped)}}}return out}Tokenizer.prototype._read_string_recursive=function(delimiter,allow_unescaped_newlines,start_sub){var current_char;var pattern;if(delimiter==="'"){pattern=this.__patterns.single_quote}else if(delimiter==='"'){pattern=this.__patterns.double_quote}else if(delimiter==="`"){pattern=this.__patterns.template_text}else if(delimiter==="}"){pattern=this.__patterns.template_expression}var resulting_string=pattern.read();var next="";while(this._input.hasNext()){next=this._input.next();if(next===delimiter||!allow_unescaped_newlines&&acorn.newline.test(next)){this._input.back();break}else if(next==="\\"&&this._input.hasNext()){current_char=this._input.peek();if(current_char==="x"||current_char==="u"){this.has_char_escapes=true}else if(current_char==="\r"&&this._input.peek(1)==="\n"){this._input.next()}next+=this._input.next()}else if(start_sub){if(start_sub==="${"&&next==="$"&&this._input.peek()==="{"){next+=this._input.next()}if(start_sub===next){if(delimiter==="`"){next+=this._read_string_recursive("}",allow_unescaped_newlines,"`")}else{next+=this._read_string_recursive("`",allow_unescaped_newlines,"${")}if(this._input.hasNext()){next+=this._input.next()}}}next+=pattern.read();resulting_string+=next}return resulting_string};module.exports.Tokenizer=Tokenizer;module.exports.TOKEN=TOKEN;module.exports.positionable_operators=positionable_operators.slice();module.exports.line_starters=line_starters.slice()},{"../core/directives":117,"../core/inputscanner":118,"../core/pattern":121,"../core/templatablepattern":122,"../core/tokenizer":124,"./acorn":135}],140:[function(require,module,exports){(function webpackUniversalModuleDefinition(root,factory){if(typeof exports==="object"&&typeof module==="object")module.exports=factory();else if(typeof define==="function"&&define.amd)define([],factory);else if(typeof exports==="object")exports["Meyda"]=factory();else root["Meyda"]=factory()})(window,(function(){return function(modules){var installedModules={};function __webpack_require__(moduleId){if(installedModules[moduleId]){return installedModules[moduleId].exports}var module=installedModules[moduleId]={i:moduleId,l:false,exports:{}};modules[moduleId].call(module.exports,module,module.exports,__webpack_require__);module.l=true;return module.exports}__webpack_require__.m=modules;__webpack_require__.c=installedModules;__webpack_require__.d=function(exports,name,getter){if(!__webpack_require__.o(exports,name)){Object.defineProperty(exports,name,{enumerable:true,get:getter})}};__webpack_require__.r=function(exports){if(typeof Symbol!=="undefined"&&Symbol.toStringTag){Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}Object.defineProperty(exports,"__esModule",{value:true})};__webpack_require__.t=function(value,mode){if(mode&1)value=__webpack_require__(value);if(mode&8)return value;if(mode&4&&typeof value==="object"&&value&&value.__esModule)return value;var ns=Object.create(null);__webpack_require__.r(ns);Object.defineProperty(ns,"default",{enumerable:true,value:value});if(mode&2&&typeof value!="string")for(var key in value)__webpack_require__.d(ns,key,function(key){return value[key]}.bind(null,key));return ns};__webpack_require__.n=function(module){var getter=module&&module.__esModule?function getDefault(){return module["default"]}:function getModuleExports(){return module};__webpack_require__.d(getter,"a",getter);return getter};__webpack_require__.o=function(object,property){return Object.prototype.hasOwnProperty.call(object,property)};__webpack_require__.p="";return __webpack_require__(__webpack_require__.s="./src/index.js")}({"./node_modules/assert/assert.js": /*!***************************************!*\ !*** ./node_modules/assert/assert.js ***! \***************************************/ /*! no static exports found */function(module,exports,__webpack_require__){"use strict";(function(global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a,b){if(a===b){return 0}var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function truncate(s,n){if(typeof s==="string"){return s.length=0;i--){if(ka[i]!==kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key],strict,actualVisitedObjects))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected,false)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.notDeepStrictEqual=notDeepStrictEqual;function notDeepStrictEqual(actual,expected,message){if(_deepEqual(actual,expected,true)){fail(actual,expected,message,"notDeepStrictEqual",notDeepStrictEqual)}}assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}try{if(actual instanceof expected){return true}}catch(e){}if(Error.isPrototypeOf(expected)){return false}return expected.call({},actual)===true}function _tryBlock(block){var error;try{block()}catch(e){error=e}return error}function _throws(shouldThrow,block,expected,message){var actual;if(typeof block!=="function"){throw new TypeError('"block" argument must be a function')}if(typeof expected==="string"){message=expected;expected=null}actual=_tryBlock(block);message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}var userProvidedMessage=typeof message==="string";var isUnwantedException=!shouldThrow&&util.isError(actual);var isUnexpectedException=!shouldThrow&&actual&&!expected;if(isUnwantedException&&userProvidedMessage&&expectedException(actual,expected)||isUnexpectedException){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws(true,block,error,message)};assert.doesNotThrow=function(block,error,message){_throws(false,block,error,message)};assert.ifError=function(err){if(err)throw err};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}}).call(this,__webpack_require__(/*! ./../webpack-stream/node_modules/webpack/buildin/global.js */"./node_modules/webpack-stream/node_modules/webpack/buildin/global.js"))},"./node_modules/dct/index.js": /*!***********************************!*\ !*** ./node_modules/dct/index.js ***! \***********************************/ /*! no static exports found */function(module,exports,__webpack_require__){module.exports=__webpack_require__(/*! ./src/dct.js */"./node_modules/dct/src/dct.js")},"./node_modules/dct/src/dct.js": /*!*************************************!*\ !*** ./node_modules/dct/src/dct.js ***! \*************************************/ /*! no static exports found */function(module,exports){var cosMap=null;var memoizeCosines=function(N){cosMap=cosMap||{};cosMap[N]=new Array(N*N);var PI_N=Math.PI/N;for(var k=0;k1){for(var i=1;i=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}}));for(var x=args[i];i=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};inspect.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach((function(val,idx){hash[val]=true}));return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map((function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)}))}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i-1){if(array){str=str.split("\n").map((function(line){return" "+line})).join("\n").substr(2)}else{str="\n"+str.split("\n").map((function(line){return" "+line})).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce((function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1}),0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=__webpack_require__(/*! ./support/isBuffer */"./node_modules/webpack-stream/node_modules/util/support/isBufferBrowser.js");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=__webpack_require__(/*! inherits */"./node_modules/inherits/inherits_browser.js");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}var kCustomPromisifiedSymbol=typeof Symbol!=="undefined"?Symbol("util.promisify.custom"):undefined;exports.promisify=function promisify(original){if(typeof original!=="function")throw new TypeError('The "original" argument must be of type Function');if(kCustomPromisifiedSymbol&&original[kCustomPromisifiedSymbol]){var fn=original[kCustomPromisifiedSymbol];if(typeof fn!=="function"){throw new TypeError('The "util.promisify.custom" argument must be of type Function')}Object.defineProperty(fn,kCustomPromisifiedSymbol,{value:fn,enumerable:false,writable:false,configurable:true});return fn}function fn(){var promiseResolve,promiseReject;var promise=new Promise((function(resolve,reject){promiseResolve=resolve;promiseReject=reject}));var args=[];for(var i=0;icurrentBandEnd){bbLimits[currentBand++]=i;currentBandEnd=currentBand*args.barkScale[normalisedSpectrum.length-1]/NUM_BARK_BANDS}}bbLimits[NUM_BARK_BANDS]=normalisedSpectrum.length-1;for(var _i=0;_imax){max=loudnessValue.specific[i]}}var spread=Math.pow((loudnessValue.total-max)/loudnessValue.total,2);return spread}},"./src/extractors/powerSpectrum.js": /*!*****************************************!*\ !*** ./src/extractors/powerSpectrum.js ***! \*****************************************/ /*! exports provided: default */function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}__webpack_exports__["default"]=function(){if(_typeof(arguments[0].ampSpectrum)!=="object"){throw new TypeError}var powerSpectrum=new Float32Array(arguments[0].ampSpectrum.length);for(var i=0;ithreshold&&n>=0){ec-=ampspec[n];--n}return(n+1)*nyqBin}},"./src/extractors/spectralSkewness.js": /*!********************************************!*\ !*** ./src/extractors/spectralSkewness.js ***! \********************************************/ /*! exports provided: default */function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);var _extractorUtilities__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./extractorUtilities */"./src/extractors/extractorUtilities.js");function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}__webpack_exports__["default"]=function(args){if(_typeof(args.ampSpectrum)!=="object"){throw new TypeError}var mu1=Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(1,args.ampSpectrum);var mu2=Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(2,args.ampSpectrum);var mu3=Object(_extractorUtilities__WEBPACK_IMPORTED_MODULE_0__["mu"])(3,args.ampSpectrum);var numerator=2*Math.pow(mu1,3)-3*mu1*mu2+mu3;var denominator=Math.pow(Math.sqrt(mu2-Math.pow(mu1,2)),3);return numerator/denominator}},"./src/extractors/spectralSlope.js": /*!*****************************************!*\ !*** ./src/extractors/spectralSlope.js ***! \*****************************************/ /*! exports provided: default */function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}__webpack_exports__["default"]=function(args){if(_typeof(args.ampSpectrum)!=="object"){throw new TypeError}var ampSum=0;var freqSum=0;var freqs=new Float32Array(args.ampSpectrum.length);var powFreqSum=0;var ampFreqSum=0;for(var i=0;i=0&&arguments[0].signal[i]<0||arguments[0].signal[i-1]<0&&arguments[0].signal[i]>=0){zcr++}}return zcr}},"./src/featureExtractors.js": /*!**********************************!*\ !*** ./src/featureExtractors.js ***! \**********************************/ /*! exports provided: buffer, rms, energy, complexSpectrum, spectralSlope, spectralCentroid, spectralRolloff, spectralFlatness, spectralSpread, spectralSkewness, spectralKurtosis, amplitudeSpectrum, zcr, loudness, perceptualSpread, perceptualSharpness, powerSpectrum, mfcc, chroma, spectralFlux */function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);__webpack_require__.d(__webpack_exports__,"buffer",(function(){return buffer}));__webpack_require__.d(__webpack_exports__,"complexSpectrum",(function(){return complexSpectrum}));__webpack_require__.d(__webpack_exports__,"amplitudeSpectrum",(function(){return amplitudeSpectrum}));var _extractors_rms__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./extractors/rms */"./src/extractors/rms.js");__webpack_require__.d(__webpack_exports__,"rms",(function(){return _extractors_rms__WEBPACK_IMPORTED_MODULE_0__["default"]}));var _extractors_energy__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! ./extractors/energy */"./src/extractors/energy.js");__webpack_require__.d(__webpack_exports__,"energy",(function(){return _extractors_energy__WEBPACK_IMPORTED_MODULE_1__["default"]}));var _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! ./extractors/spectralSlope */"./src/extractors/spectralSlope.js");__webpack_require__.d(__webpack_exports__,"spectralSlope",(function(){return _extractors_spectralSlope__WEBPACK_IMPORTED_MODULE_2__["default"]}));var _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! ./extractors/spectralCentroid */"./src/extractors/spectralCentroid.js");__webpack_require__.d(__webpack_exports__,"spectralCentroid",(function(){return _extractors_spectralCentroid__WEBPACK_IMPORTED_MODULE_3__["default"]}));var _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__=__webpack_require__(/*! ./extractors/spectralRolloff */"./src/extractors/spectralRolloff.js");__webpack_require__.d(__webpack_exports__,"spectralRolloff",(function(){return _extractors_spectralRolloff__WEBPACK_IMPORTED_MODULE_4__["default"]}));var _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__=__webpack_require__(/*! ./extractors/spectralFlatness */"./src/extractors/spectralFlatness.js");__webpack_require__.d(__webpack_exports__,"spectralFlatness",(function(){return _extractors_spectralFlatness__WEBPACK_IMPORTED_MODULE_5__["default"]}));var _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__=__webpack_require__(/*! ./extractors/spectralSpread */"./src/extractors/spectralSpread.js");__webpack_require__.d(__webpack_exports__,"spectralSpread",(function(){return _extractors_spectralSpread__WEBPACK_IMPORTED_MODULE_6__["default"]}));var _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__=__webpack_require__(/*! ./extractors/spectralSkewness */"./src/extractors/spectralSkewness.js");__webpack_require__.d(__webpack_exports__,"spectralSkewness",(function(){return _extractors_spectralSkewness__WEBPACK_IMPORTED_MODULE_7__["default"]}));var _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__=__webpack_require__(/*! ./extractors/spectralKurtosis */"./src/extractors/spectralKurtosis.js");__webpack_require__.d(__webpack_exports__,"spectralKurtosis",(function(){return _extractors_spectralKurtosis__WEBPACK_IMPORTED_MODULE_8__["default"]}));var _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__=__webpack_require__(/*! ./extractors/zcr */"./src/extractors/zcr.js");__webpack_require__.d(__webpack_exports__,"zcr",(function(){return _extractors_zcr__WEBPACK_IMPORTED_MODULE_9__["default"]}));var _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__=__webpack_require__(/*! ./extractors/loudness */"./src/extractors/loudness.js");__webpack_require__.d(__webpack_exports__,"loudness",(function(){return _extractors_loudness__WEBPACK_IMPORTED_MODULE_10__["default"]}));var _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__=__webpack_require__(/*! ./extractors/perceptualSpread */"./src/extractors/perceptualSpread.js");__webpack_require__.d(__webpack_exports__,"perceptualSpread",(function(){return _extractors_perceptualSpread__WEBPACK_IMPORTED_MODULE_11__["default"]}));var _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__=__webpack_require__(/*! ./extractors/perceptualSharpness */"./src/extractors/perceptualSharpness.js");__webpack_require__.d(__webpack_exports__,"perceptualSharpness",(function(){return _extractors_perceptualSharpness__WEBPACK_IMPORTED_MODULE_12__["default"]}));var _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__=__webpack_require__(/*! ./extractors/mfcc */"./src/extractors/mfcc.js");__webpack_require__.d(__webpack_exports__,"mfcc",(function(){return _extractors_mfcc__WEBPACK_IMPORTED_MODULE_13__["default"]}));var _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__=__webpack_require__(/*! ./extractors/chroma */"./src/extractors/chroma.js");__webpack_require__.d(__webpack_exports__,"chroma",(function(){return _extractors_chroma__WEBPACK_IMPORTED_MODULE_14__["default"]}));var _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__=__webpack_require__(/*! ./extractors/powerSpectrum */"./src/extractors/powerSpectrum.js");__webpack_require__.d(__webpack_exports__,"powerSpectrum",(function(){return _extractors_powerSpectrum__WEBPACK_IMPORTED_MODULE_15__["default"]}));var _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__=__webpack_require__(/*! ./extractors/spectralFlux */"./src/extractors/spectralFlux.js");__webpack_require__.d(__webpack_exports__,"spectralFlux",(function(){return _extractors_spectralFlux__WEBPACK_IMPORTED_MODULE_16__["default"]}));var buffer=function buffer(args){return args.signal};var complexSpectrum=function complexSpectrum(args){return args.complexSpectrum};var amplitudeSpectrum=function amplitudeSpectrum(args){return args.ampSpectrum}},"./src/index.js": /*!**********************!*\ !*** ./src/index.js ***! \**********************/ /*! no static exports found */function(module,exports,__webpack_require__){module.exports=__webpack_require__(/*! ./main */"./src/main.js")["default"]},"./src/main.js": /*!*********************!*\ !*** ./src/main.js ***! \*********************/ /*! exports provided: default */function(module,__webpack_exports__,__webpack_require__){"use strict";__webpack_require__.r(__webpack_exports__);var _utilities__WEBPACK_IMPORTED_MODULE_0__=__webpack_require__(/*! ./utilities */"./src/utilities.js");var _featureExtractors__WEBPACK_IMPORTED_MODULE_1__=__webpack_require__(/*! ./featureExtractors */"./src/featureExtractors.js");var fftjs__WEBPACK_IMPORTED_MODULE_2__=__webpack_require__(/*! fftjs */"./node_modules/fftjs/dist/fft.js");var fftjs__WEBPACK_IMPORTED_MODULE_2___default=__webpack_require__.n(fftjs__WEBPACK_IMPORTED_MODULE_2__);var _meyda_wa__WEBPACK_IMPORTED_MODULE_3__=__webpack_require__(/*! ./meyda-wa */"./src/meyda-wa.js");function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true})}else{obj[key]=value}return obj}function _typeof(obj){if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}var Meyda={audioContext:null,spn:null,bufferSize:512,sampleRate:44100,melBands:26,chromaBands:12,callback:null,windowingFunction:"hanning",featureExtractors:_featureExtractors__WEBPACK_IMPORTED_MODULE_1__,EXTRACTION_STARTED:false,numberOfMFCCCoefficients:13,_featuresToExtract:[],windowing:_utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"],_errors:{notPow2:new Error("Meyda: Buffer size must be a power of 2, e.g. 64 or 512"),featureUndef:new Error("Meyda: No features defined."),invalidFeatureFmt:new Error("Meyda: Invalid feature format"),invalidInput:new Error("Meyda: Invalid input."),noAC:new Error("Meyda: No AudioContext specified."),noSource:new Error("Meyda: No source node specified.")},createMeydaAnalyzer:function createMeydaAnalyzer(options){return new _meyda_wa__WEBPACK_IMPORTED_MODULE_3__["MeydaAnalyzer"](options,Object.assign({},Meyda))},extract:function extract(feature,signal,previousSignal){var _this=this;if(!signal)throw this._errors.invalidInput;else if(_typeof(signal)!="object")throw this._errors.invalidInput;else if(!feature)throw this._errors.featureUndef;else if(!_utilities__WEBPACK_IMPORTED_MODULE_0__["isPowerOfTwo"](signal.length))throw this._errors.notPow2;if(typeof this.barkScale=="undefined"||this.barkScale.length!=this.bufferSize){this.barkScale=_utilities__WEBPACK_IMPORTED_MODULE_0__["createBarkScale"](this.bufferSize,this.sampleRate,this.bufferSize)}if(typeof this.melFilterBank=="undefined"||this.barkScale.length!=this.bufferSize||this.melFilterBank.length!=this.melBands){this.melFilterBank=_utilities__WEBPACK_IMPORTED_MODULE_0__["createMelFilterBank"](Math.max(this.melBands,this.numberOfMFCCCoefficients),this.sampleRate,this.bufferSize)}if(typeof this.chromaFilterBank=="undefined"||this.chromaFilterBank.length!=this.chromaBands){this.chromaFilterBank=_utilities__WEBPACK_IMPORTED_MODULE_0__["createChromaFilterBank"](this.chromaBands,this.sampleRate,this.bufferSize)}if(typeof signal.buffer=="undefined"){this.signal=_utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal)}else{this.signal=signal}var preparedSignal=prepareSignalWithSpectrum(signal,this.windowingFunction,this.bufferSize);this.signal=preparedSignal.windowedSignal;this.complexSpectrum=preparedSignal.complexSpectrum;this.ampSpectrum=preparedSignal.ampSpectrum;if(previousSignal){var _preparedSignal=prepareSignalWithSpectrum(previousSignal,this.windowingFunction,this.bufferSize);this.previousSignal=_preparedSignal.windowedSignal;this.previousComplexSpectrum=_preparedSignal.complexSpectrum;this.previousAmpSpectrum=_preparedSignal.ampSpectrum}var extract=function extract(feature){return _this.featureExtractors[feature]({ampSpectrum:_this.ampSpectrum,chromaFilterBank:_this.chromaFilterBank,complexSpectrum:_this.complexSpectrum,signal:_this.signal,bufferSize:_this.bufferSize,sampleRate:_this.sampleRate,barkScale:_this.barkScale,melFilterBank:_this.melFilterBank,previousSignal:_this.previousSignal,previousAmpSpectrum:_this.previousAmpSpectrum,previousComplexSpectrum:_this.previousComplexSpectrum,numberOfMFCCCoefficients:_this.numberOfMFCCCoefficients})};if(_typeof(feature)==="object"){return feature.reduce((function(acc,el){return Object.assign({},acc,_defineProperty({},el,extract(el)))}),{})}else if(typeof feature==="string"){return extract(feature)}else{throw this._errors.invalidFeatureFmt}}};var prepareSignalWithSpectrum=function prepareSignalWithSpectrum(signal,windowingFunction,bufferSize){var preparedSignal={};if(typeof signal.buffer=="undefined"){preparedSignal.signal=_utilities__WEBPACK_IMPORTED_MODULE_0__["arrayToTyped"](signal)}else{preparedSignal.signal=signal}preparedSignal.windowedSignal=_utilities__WEBPACK_IMPORTED_MODULE_0__["applyWindow"](preparedSignal.signal,windowingFunction);preparedSignal.complexSpectrum=Object(fftjs__WEBPACK_IMPORTED_MODULE_2__["fft"])(preparedSignal.windowedSignal);preparedSignal.ampSpectrum=new Float32Array(bufferSize/2);for(var i=0;i1){num/=2}return num===1}function error(message){throw new Error("Meyda: "+message)}function pointwiseBufferMult(a,b){var c=[];for(var i=0;i3&&arguments[3]!==undefined?arguments[3]:5;var octaveWidth=arguments.length>4&&arguments[4]!==undefined?arguments[4]:2;var baseC=arguments.length>5&&arguments[5]!==undefined?arguments[5]:true;var A440=arguments.length>6&&arguments[6]!==undefined?arguments[6]:440;var numOutputBins=Math.floor(bufferSize/2)+1;var frequencyBins=new Array(bufferSize).fill(0).map((function(_,i){return numFilters*hzToOctaves(sampleRate*i/bufferSize,A440)}));frequencyBins[0]=frequencyBins[1]-1.5*numFilters;var binWidthBins=frequencyBins.slice(1).map((function(v,i){return Math.max(v-frequencyBins[i])}),1).concat([1]);var halfNumFilters=Math.round(numFilters/2);var filterPeaks=new Array(numFilters).fill(0).map((function(_,i){return frequencyBins.map((function(frq){return(10*numFilters+halfNumFilters+frq-i)%numFilters-halfNumFilters}))}));var weights=filterPeaks.map((function(row,i){return row.map((function(_,j){return Math.exp(-.5*Math.pow(2*filterPeaks[i][j]/binWidthBins[j],2))}))}));weights=normalizeByColumn(weights);if(octaveWidth){var octaveWeights=frequencyBins.map((function(v){return Math.exp(-.5*Math.pow((v/numFilters-centerOctave)/octaveWidth,2))}));weights=weights.map((function(row){return row.map((function(cell,j){return cell*octaveWeights[j]}))}))}if(baseC){weights=[].concat(_toConsumableArray(weights.slice(3)),_toConsumableArray(weights.slice(0,3)))}return weights.map((function(row){return row.slice(0,numOutputBins)}))}function frame(buffer,frameLength,hopLength){if(buffer.length0;_i--){blackmanBuffer[size-_i]=blackmanBuffer[_i-1]}return blackmanBuffer}function sine(size){var coeff=Math.PI/(size-1);var sineBuffer=new Float32Array(size);for(var i=0;i0){this._emit(this._listeners[eventName],data)}if(this._starListeners.length>0){this._emit(this._starListeners,eventName,data,emitTiming.uuid)}emitTiming();return this};Nanobus.prototype.on=Nanobus.prototype.addListener=function(eventName,listener){assert.ok(typeof eventName==="string"||typeof eventName==="symbol","nanobus.on: eventName should be type string or symbol");assert.equal(typeof listener,"function","nanobus.on: listener should be type function");if(eventName==="*"){this._starListeners.push(listener)}else{if(!this._listeners[eventName])this._listeners[eventName]=[];this._listeners[eventName].push(listener)}return this};Nanobus.prototype.prependListener=function(eventName,listener){assert.ok(typeof eventName==="string"||typeof eventName==="symbol","nanobus.prependListener: eventName should be type string or symbol");assert.equal(typeof listener,"function","nanobus.prependListener: listener should be type function");if(eventName==="*"){this._starListeners.unshift(listener)}else{if(!this._listeners[eventName])this._listeners[eventName]=[];this._listeners[eventName].unshift(listener)}return this};Nanobus.prototype.once=function(eventName,listener){assert.ok(typeof eventName==="string"||typeof eventName==="symbol","nanobus.once: eventName should be type string or symbol");assert.equal(typeof listener,"function","nanobus.once: listener should be type function");var self=this;this.on(eventName,once);function once(){listener.apply(self,arguments);self.removeListener(eventName,once)}return this};Nanobus.prototype.prependOnceListener=function(eventName,listener){assert.ok(typeof eventName==="string"||typeof eventName==="symbol","nanobus.prependOnceListener: eventName should be type string or symbol");assert.equal(typeof listener,"function","nanobus.prependOnceListener: listener should be type function");var self=this;this.prependListener(eventName,once);function once(){listener.apply(self,arguments);self.removeListener(eventName,once)}return this};Nanobus.prototype.removeListener=function(eventName,listener){assert.ok(typeof eventName==="string"||typeof eventName==="symbol","nanobus.removeListener: eventName should be type string or symbol");assert.equal(typeof listener,"function","nanobus.removeListener: listener should be type function");if(eventName==="*"){this._starListeners=this._starListeners.slice();return remove(this._starListeners,listener)}else{if(typeof this._listeners[eventName]!=="undefined"){this._listeners[eventName]=this._listeners[eventName].slice()}return remove(this._listeners[eventName],listener)}function remove(arr,listener){if(!arr)return;var index=arr.indexOf(listener);if(index!==-1){splice(arr,index,1);return true}}};Nanobus.prototype.removeAllListeners=function(eventName){if(eventName){if(eventName==="*"){this._starListeners=[]}else{this._listeners[eventName]=[]}}else{this._starListeners=[];this._listeners={}}return this};Nanobus.prototype.listeners=function(eventName){var listeners=eventName!=="*"?this._listeners[eventName]:this._starListeners;var ret=[];if(listeners){var ilength=listeners.length;for(var i=0;ithis.maxAge){this.remove(key);return false}return true};LRU.prototype.get=function(key){if(typeof key!=="string")key=""+key;if(!this.cache.hasOwnProperty(key))return;var element=this.cache[key];if(!this._checkAge(key,element))return;if(this.head!==key){if(key===this.tail){this.tail=element.next;this.cache[this.tail].prev=null}else{this.cache[element.prev].next=element.next}this.cache[element.next].prev=element.prev;this.cache[this.head].next=key;element.prev=this.head;element.next=null;this.head=key}return element.value};LRU.prototype.evict=function(){if(!this.tail)return;this.remove(this.tail)}},{}],156:[function(require,module,exports){var assert=require("nanoassert");var morph=require("./lib/morph");var TEXT_NODE=3;module.exports=nanomorph;function nanomorph(oldTree,newTree,options){assert.equal(typeof oldTree,"object","nanomorph: oldTree should be an object");assert.equal(typeof newTree,"object","nanomorph: newTree should be an object");if(options&&options.childrenOnly){updateChildren(newTree,oldTree);return oldTree}assert.notEqual(newTree.nodeType,11,"nanomorph: newTree should have one root node (which is not a DocumentFragment)");return walk(newTree,oldTree)}function walk(newNode,oldNode){if(!oldNode){return newNode}else if(!newNode){return null}else if(newNode.isSameNode&&newNode.isSameNode(oldNode)){return oldNode}else if(newNode.tagName!==oldNode.tagName||getComponentId(newNode)!==getComponentId(oldNode)){return newNode}else{morph(newNode,oldNode);updateChildren(newNode,oldNode);return oldNode}}function getComponentId(node){return node.dataset?node.dataset.nanomorphComponentId:undefined}function updateChildren(newNode,oldNode){var oldChild,newChild,morphed,oldMatch;var offset=0;for(var i=0;;i++){oldChild=oldNode.childNodes[i];newChild=newNode.childNodes[i-offset];if(!oldChild&&!newChild){break}else if(!newChild){oldNode.removeChild(oldChild);i--}else if(!oldChild){oldNode.appendChild(newChild);offset++}else if(same(newChild,oldChild)){morphed=walk(newChild,oldChild);if(morphed!==oldChild){oldNode.replaceChild(morphed,oldChild);offset++}}else{oldMatch=null;for(var j=i;j=0;--i){attr=newAttrs[i];attrName=attr.name;attrNamespaceURI=attr.namespaceURI;attrValue=attr.value;if(attrNamespaceURI){attrName=attr.localName||attrName;fromValue=oldNode.getAttributeNS(attrNamespaceURI,attrName);if(fromValue!==attrValue){oldNode.setAttributeNS(attrNamespaceURI,attrName,attrValue)}}else{if(!oldNode.hasAttribute(attrName)){oldNode.setAttribute(attrName,attrValue)}else{fromValue=oldNode.getAttribute(attrName);if(fromValue!==attrValue){if(attrValue==="null"||attrValue==="undefined"){oldNode.removeAttribute(attrName)}else{oldNode.setAttribute(attrName,attrValue)}}}}}for(var j=oldAttrs.length-1;j>=0;--j){attr=oldAttrs[j];if(attr.specified!==false){attrName=attr.name;attrNamespaceURI=attr.namespaceURI;if(attrNamespaceURI){attrName=attr.localName||attrName;if(!newNode.hasAttributeNS(attrNamespaceURI,attrName)){oldNode.removeAttributeNS(attrNamespaceURI,attrName)}}else{if(!newNode.hasAttributeNS(null,attrName)){oldNode.removeAttribute(attrName)}}}}}function copyEvents(newNode,oldNode){for(var i=0;i0){cb=self.queue.shift();cb(idleDeadline)}self.scheduled=false;if(self.queue.length)self.schedule()}))};NanoScheduler.prototype.setTimeout=function(cb){setTimeout(cb,0,{timeRemaining:function(){return 1}})};module.exports=createScheduler},{assert:141}],163:[function(require,module,exports){var scheduler=require("nanoscheduler")();var assert=require("assert");var perf;nanotiming.disabled=true;try{perf=window.performance;nanotiming.disabled=window.localStorage.DISABLE_NANOTIMING==="true"||!perf.mark}catch(e){}module.exports=nanotiming;function nanotiming(name){assert.equal(typeof name,"string","nanotiming: name should be type string");if(nanotiming.disabled)return noop;var uuid=(perf.now()*1e4).toFixed()%Number.MAX_SAFE_INTEGER;var startName="start-"+uuid+"-"+name;perf.mark(startName);function end(cb){var endName="end-"+uuid+"-"+name;perf.mark(endName);scheduler.push((function(){var err=null;try{var measureName=name+" ["+uuid+"]";perf.measure(measureName,startName,endName);perf.clearMarks(startName);perf.clearMarks(endName)}catch(e){err=e}if(cb)cb(err,name)}))}end.uuid=uuid;return end}function noop(cb){if(cb){scheduler.push((function(){cb(new Error("nanotiming: performance API unavailable"))}))}}},{assert:141,nanoscheduler:162}],164:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ "use strict";var getOwnPropertySymbols=Object.getOwnPropertySymbols;var hasOwnProperty=Object.prototype.hasOwnProperty;var propIsEnumerable=Object.prototype.propertyIsEnumerable;function toObject(val){if(val===null||val===undefined){throw new TypeError("Object.assign cannot be called with null or undefined")}return Object(val)}function shouldUseNative(){try{if(!Object.assign){return false}var test1=new String("abc");test1[5]="de";if(Object.getOwnPropertyNames(test1)[0]==="5"){return false}var test2={};for(var i=0;i<10;i++){test2["_"+String.fromCharCode(i)]=i}var order2=Object.getOwnPropertyNames(test2).map((function(n){return test2[n]}));if(order2.join("")!=="0123456789"){return false}var test3={};"abcdefghijklmnopqrst".split("").forEach((function(letter){test3[letter]=letter}));if(Object.keys(Object.assign({},test3)).join("")!=="abcdefghijklmnopqrst"){return false}return true}catch(err){return false}}module.exports=shouldUseNative()?Object.assign:function(target,source){var from;var to=toObject(target);var symbols;for(var s=1;s2?arr.slice(2):arr;arr[0]=arr[0].replace(/^ {4}at /,"");return"\n"+arr.join("\n")}},{assert:19}],166:[function(require,module,exports){var hasMap=typeof Map==="function"&&Map.prototype;var mapSizeDescriptor=Object.getOwnPropertyDescriptor&&hasMap?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null;var mapSize=hasMap&&mapSizeDescriptor&&typeof mapSizeDescriptor.get==="function"?mapSizeDescriptor.get:null;var mapForEach=hasMap&&Map.prototype.forEach;var hasSet=typeof Set==="function"&&Set.prototype;var setSizeDescriptor=Object.getOwnPropertyDescriptor&&hasSet?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null;var setSize=hasSet&&setSizeDescriptor&&typeof setSizeDescriptor.get==="function"?setSizeDescriptor.get:null;var setForEach=hasSet&&Set.prototype.forEach;var hasWeakMap=typeof WeakMap==="function"&&WeakMap.prototype;var weakMapHas=hasWeakMap?WeakMap.prototype.has:null;var hasWeakSet=typeof WeakSet==="function"&&WeakSet.prototype;var weakSetHas=hasWeakSet?WeakSet.prototype.has:null;var hasWeakRef=typeof WeakRef==="function"&&WeakRef.prototype;var weakRefDeref=hasWeakRef?WeakRef.prototype.deref:null;var booleanValueOf=Boolean.prototype.valueOf;var objectToString=Object.prototype.toString;var functionToString=Function.prototype.toString;var $match=String.prototype.match;var $slice=String.prototype.slice;var $replace=String.prototype.replace;var $toUpperCase=String.prototype.toUpperCase;var $toLowerCase=String.prototype.toLowerCase;var $test=RegExp.prototype.test;var $concat=Array.prototype.concat;var $join=Array.prototype.join;var $arrSlice=Array.prototype.slice;var $floor=Math.floor;var bigIntValueOf=typeof BigInt==="function"?BigInt.prototype.valueOf:null;var gOPS=Object.getOwnPropertySymbols;var symToString=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?Symbol.prototype.toString:null;var hasShammedSymbols=typeof Symbol==="function"&&typeof Symbol.iterator==="object";var toStringTag=typeof Symbol==="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===hasShammedSymbols?"object":"symbol")?Symbol.toStringTag:null;var isEnumerable=Object.prototype.propertyIsEnumerable;var gPO=(typeof Reflect==="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(O){return O.__proto__}:null);function addNumericSeparator(num,str){if(num===Infinity||num===-Infinity||num!==num||num&&num>-1e3&&num<1e3||$test.call(/e/,str)){return str}var sepRegex=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof num==="number"){var int=num<0?-$floor(-num):$floor(num);if(int!==num){var intStr=String(int);var dec=$slice.call(str,intStr.length+1);return $replace.call(intStr,sepRegex,"$&_")+"."+$replace.call($replace.call(dec,/([0-9]{3})/g,"$&_"),/_$/,"")}}return $replace.call(str,sepRegex,"$&_")}var inspectCustom=require("./util.inspect").custom;var inspectSymbol=inspectCustom&&isSymbol(inspectCustom)?inspectCustom:null;module.exports=function inspect_(obj,options,depth,seen){var opts=options||{};if(has(opts,"quoteStyle")&&(opts.quoteStyle!=="single"&&opts.quoteStyle!=="double")){throw new TypeError('option "quoteStyle" must be "single" or "double"')}if(has(opts,"maxStringLength")&&(typeof opts.maxStringLength==="number"?opts.maxStringLength<0&&opts.maxStringLength!==Infinity:opts.maxStringLength!==null)){throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`')}var customInspect=has(opts,"customInspect")?opts.customInspect:true;if(typeof customInspect!=="boolean"&&customInspect!=="symbol"){throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`")}if(has(opts,"indent")&&opts.indent!==null&&opts.indent!=="\t"&&!(parseInt(opts.indent,10)===opts.indent&&opts.indent>0)){throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`')}if(has(opts,"numericSeparator")&&typeof opts.numericSeparator!=="boolean"){throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`')}var numericSeparator=opts.numericSeparator;if(typeof obj==="undefined"){return"undefined"}if(obj===null){return"null"}if(typeof obj==="boolean"){return obj?"true":"false"}if(typeof obj==="string"){return inspectString(obj,opts)}if(typeof obj==="number"){if(obj===0){return Infinity/obj>0?"0":"-0"}var str=String(obj);return numericSeparator?addNumericSeparator(obj,str):str}if(typeof obj==="bigint"){var bigIntStr=String(obj)+"n";return numericSeparator?addNumericSeparator(obj,bigIntStr):bigIntStr}var maxDepth=typeof opts.depth==="undefined"?5:opts.depth;if(typeof depth==="undefined"){depth=0}if(depth>=maxDepth&&maxDepth>0&&typeof obj==="object"){return isArray(obj)?"[Array]":"[Object]"}var indent=getIndent(opts,depth);if(typeof seen==="undefined"){seen=[]}else if(indexOf(seen,obj)>=0){return"[Circular]"}function inspect(value,from,noIndent){if(from){seen=$arrSlice.call(seen);seen.push(from)}if(noIndent){var newOpts={depth:opts.depth};if(has(opts,"quoteStyle")){newOpts.quoteStyle=opts.quoteStyle}return inspect_(value,newOpts,depth+1,seen)}return inspect_(value,opts,depth+1,seen)}if(typeof obj==="function"){var name=nameOf(obj);var keys=arrObjKeys(obj,inspect);return"[Function"+(name?": "+name:" (anonymous)")+"]"+(keys.length>0?" { "+$join.call(keys,", ")+" }":"")}if(isSymbol(obj)){var symString=hasShammedSymbols?$replace.call(String(obj),/^(Symbol\(.*\))_[^)]*$/,"$1"):symToString.call(obj);return typeof obj==="object"&&!hasShammedSymbols?markBoxed(symString):symString}if(isElement(obj)){var s="<"+$toLowerCase.call(String(obj.nodeName));var attrs=obj.attributes||[];for(var i=0;i";return s}if(isArray(obj)){if(obj.length===0){return"[]"}var xs=arrObjKeys(obj,inspect);if(indent&&!singleLineValues(xs)){return"["+indentedJoin(xs,indent)+"]"}return"[ "+$join.call(xs,", ")+" ]"}if(isError(obj)){var parts=arrObjKeys(obj,inspect);if("cause"in obj&&!isEnumerable.call(obj,"cause")){return"{ ["+String(obj)+"] "+$join.call($concat.call("[cause]: "+inspect(obj.cause),parts),", ")+" }"}if(parts.length===0){return"["+String(obj)+"]"}return"{ ["+String(obj)+"] "+$join.call(parts,", ")+" }"}if(typeof obj==="object"&&customInspect){if(inspectSymbol&&typeof obj[inspectSymbol]==="function"){return obj[inspectSymbol]()}else if(customInspect!=="symbol"&&typeof obj.inspect==="function"){return obj.inspect()}}if(isMap(obj)){var mapParts=[];mapForEach.call(obj,(function(value,key){mapParts.push(inspect(key,obj,true)+" => "+inspect(value,obj))}));return collectionOf("Map",mapSize.call(obj),mapParts,indent)}if(isSet(obj)){var setParts=[];setForEach.call(obj,(function(value){setParts.push(inspect(value,obj))}));return collectionOf("Set",setSize.call(obj),setParts,indent)}if(isWeakMap(obj)){return weakCollectionOf("WeakMap")}if(isWeakSet(obj)){return weakCollectionOf("WeakSet")}if(isWeakRef(obj)){return weakCollectionOf("WeakRef")}if(isNumber(obj)){return markBoxed(inspect(Number(obj)))}if(isBigInt(obj)){return markBoxed(inspect(bigIntValueOf.call(obj)))}if(isBoolean(obj)){return markBoxed(booleanValueOf.call(obj))}if(isString(obj)){return markBoxed(inspect(String(obj)))}if(!isDate(obj)&&!isRegExp(obj)){var ys=arrObjKeys(obj,inspect);var isPlainObject=gPO?gPO(obj)===Object.prototype:obj instanceof Object||obj.constructor===Object;var protoTag=obj instanceof Object?"":"null prototype";var stringTag=!isPlainObject&&toStringTag&&Object(obj)===obj&&toStringTag in obj?$slice.call(toStr(obj),8,-1):protoTag?"Object":"";var constructorTag=isPlainObject||typeof obj.constructor!=="function"?"":obj.constructor.name?obj.constructor.name+" ":"";var tag=constructorTag+(stringTag||protoTag?"["+$join.call($concat.call([],stringTag||[],protoTag||[]),": ")+"] ":"");if(ys.length===0){return tag+"{}"}if(indent){return tag+"{"+indentedJoin(ys,indent)+"}"}return tag+"{ "+$join.call(ys,", ")+" }"}return String(obj)};function wrapQuotes(s,defaultStyle,opts){var quoteChar=(opts.quoteStyle||defaultStyle)==="double"?'"':"'";return quoteChar+s+quoteChar}function quote(s){return $replace.call(String(s),/"/g,""")}function isArray(obj){return toStr(obj)==="[object Array]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isDate(obj){return toStr(obj)==="[object Date]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isRegExp(obj){return toStr(obj)==="[object RegExp]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isError(obj){return toStr(obj)==="[object Error]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isString(obj){return toStr(obj)==="[object String]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isNumber(obj){return toStr(obj)==="[object Number]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isBoolean(obj){return toStr(obj)==="[object Boolean]"&&(!toStringTag||!(typeof obj==="object"&&toStringTag in obj))}function isSymbol(obj){if(hasShammedSymbols){return obj&&typeof obj==="object"&&obj instanceof Symbol}if(typeof obj==="symbol"){return true}if(!obj||typeof obj!=="object"||!symToString){return false}try{symToString.call(obj);return true}catch(e){}return false}function isBigInt(obj){if(!obj||typeof obj!=="object"||!bigIntValueOf){return false}try{bigIntValueOf.call(obj);return true}catch(e){}return false}var hasOwn=Object.prototype.hasOwnProperty||function(key){return key in this};function has(obj,key){return hasOwn.call(obj,key)}function toStr(obj){return objectToString.call(obj)}function nameOf(f){if(f.name){return f.name}var m=$match.call(functionToString.call(f),/^function\s*([\w$]+)/);if(m){return m[1]}return null}function indexOf(xs,x){if(xs.indexOf){return xs.indexOf(x)}for(var i=0,l=xs.length;iopts.maxStringLength){var remaining=str.length-opts.maxStringLength;var trailer="... "+remaining+" more character"+(remaining>1?"s":"");return inspectString($slice.call(str,0,opts.maxStringLength),opts)+trailer}var s=$replace.call($replace.call(str,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,lowbyte);return wrapQuotes(s,"single",opts)}function lowbyte(c){var n=c.charCodeAt(0);var x={8:"b",9:"t",10:"n",12:"f",13:"r"}[n];if(x){return"\\"+x}return"\\x"+(n<16?"0":"")+$toUpperCase.call(n.toString(16))}function markBoxed(str){return"Object("+str+")"}function weakCollectionOf(type){return type+" { ? }"}function collectionOf(type,size,entries,indent){var joinedEntries=indent?indentedJoin(entries,indent):$join.call(entries,", ");return type+" ("+size+") {"+joinedEntries+"}"}function singleLineValues(xs){for(var i=0;i=0){return false}}return true}function getIndent(opts,depth){var baseIndent;if(opts.indent==="\t"){baseIndent="\t"}else if(typeof opts.indent==="number"&&opts.indent>0){baseIndent=$join.call(Array(opts.indent+1)," ")}else{return null}return{base:baseIndent,prev:$join.call(Array(depth+1),baseIndent)}}function indentedJoin(xs,indent){if(xs.length===0){return""}var lineJoiner="\n"+indent.prev+indent.base;return lineJoiner+$join.call(xs,","+lineJoiner)+"\n"+indent.prev}function arrObjKeys(obj,inspect){var isArr=isArray(obj);var xs=[];if(isArr){xs.length=obj.length;for(var i=0;i0){eachMutation(nodes[i].childNodes,fn)}}}},{"global/document":84,"global/window":85}],168:[function(require,module,exports){var scheduler=require("nanoscheduler")();var assert=require("assert");var entryTypes=["frame","measure","navigation","resource","longtask"];module.exports=onPerformance;function onPerformance(cb){assert.equal(typeof cb,"function","on-performance: cb should be type function");var PerformanceObserver=typeof window!=="undefined"&&window.PerformanceObserver;if(!PerformanceObserver)return;if(window._onperformance){window._onperformance.push(cb);return stop}window._onperformance=[cb];var observer=new PerformanceObserver(parseEntries);setTimeout((function(){parseEntries(window.performance);observer.observe({entryTypes:entryTypes})}),0);return stop;function stop(){window._onperformance.splice(window._onperformance.indexOf(cb),1)}function parseEntries(list){list.getEntries().forEach((function(entry){scheduler.push((function(){clear(entry);window._onperformance.forEach((function(cb){cb(entry)}))}))}))}function clear(entry){var type=entry.entryType;if(type==="measure")window.performance.clearMeasures(entry.name);else if(type==="resource")window.performance.clearResourceTimings()}}},{assert:141,nanoscheduler:162}],169:[function(require,module,exports){exports.encode=function(obj){var str="";for(var i in obj){if(obj.hasOwnProperty(i)){if(str.length)str+="&";str+=encodeURIComponent(i)+"="+encodeURIComponent(obj[i])}}return str};exports.decode=function(qs){var qry={};var pairs=qs.split("&");for(var i=0,l=pairs.length;i=2?pluck(path)(object):pluck(path)}function pluck(path){path=typeof path==="string"?String(path).trim().split("."):path;if(path.length<2){path=path[0];return pluckSingle}else{var l=path.length;return pluckPath}function pluckSingle(object){return object[path]}function pluckPath(object){for(var i=0;i=10||num%1===0){return(neg?"-":"")+num.toFixed(0)+" "+unit}else{return(neg?"-":"")+num.toFixed(1)+" "+unit}}},{}],174:[function(require,module,exports){var process=module.exports={};var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}(function(){try{if(typeof setTimeout==="function"){cachedSetTimeout=setTimeout}else{cachedSetTimeout=defaultSetTimout}}catch(e){cachedSetTimeout=defaultSetTimout}try{if(typeof clearTimeout==="function"){cachedClearTimeout=clearTimeout}else{cachedClearTimeout=defaultClearTimeout}}catch(e){cachedClearTimeout=defaultClearTimeout}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){return setTimeout(fun,0)}if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0)}try{return cachedSetTimeout(fun,0)}catch(e){try{return cachedSetTimeout.call(null,fun,0)}catch(e){return cachedSetTimeout.call(this,fun,0)}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){return clearTimeout(marker)}if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker)}try{return cachedClearTimeout(marker)}catch(e){try{return cachedClearTimeout.call(null,marker)}catch(e){return cachedClearTimeout.call(this,marker)}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue)}else{queueIndex=-1}if(queue.length){drainQueue()}}function drainQueue(){if(draining){return}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i-1){return val.split(",")}return val};var isoSentinel="utf8=%26%2310003%3B";var charsetSentinel="utf8=%E2%9C%93";var parseValues=function parseQueryStringValues(str,options){var obj={};var cleanStr=options.ignoreQueryPrefix?str.replace(/^\?/,""):str;var limit=options.parameterLimit===Infinity?undefined:options.parameterLimit;var parts=cleanStr.split(options.delimiter,limit);var skipIndex=-1;var i;var charset=options.charset;if(options.charsetSentinel){for(i=0;i-1){val=isArray(val)?[val]:val}if(has.call(obj,key)){obj[key]=utils.combine(obj[key],val)}else{obj[key]=val}}return obj};var parseObject=function(chain,val,options,valuesParsed){var leaf=valuesParsed?val:parseArrayValue(val,options);for(var i=chain.length-1;i>=0;--i){var obj;var root=chain[i];if(root==="[]"&&options.parseArrays){obj=[].concat(leaf)}else{obj=options.plainObjects?Object.create(null):{};var cleanRoot=root.charAt(0)==="["&&root.charAt(root.length-1)==="]"?root.slice(1,-1):root;var index=parseInt(cleanRoot,10);if(!options.parseArrays&&cleanRoot===""){obj={0:leaf}}else if(!isNaN(index)&&root!==cleanRoot&&String(index)===cleanRoot&&index>=0&&(options.parseArrays&&index<=options.arrayLimit)){obj=[];obj[index]=leaf}else{obj[cleanRoot]=leaf}}leaf=obj}return leaf};var parseKeys=function parseQueryStringKeys(givenKey,val,options,valuesParsed){if(!givenKey){return}var key=options.allowDots?givenKey.replace(/\.([^.[]+)/g,"[$1]"):givenKey;var brackets=/(\[[^[\]]*])/;var child=/(\[[^[\]]*])/g;var segment=options.depth>0&&brackets.exec(key);var parent=segment?key.slice(0,segment.index):key;var keys=[];if(parent){if(!options.plainObjects&&has.call(Object.prototype,parent)){if(!options.allowPrototypes){return}}keys.push(parent)}var i=0;while(options.depth>0&&(segment=child.exec(key))!==null&&i0?obj.join(",")||null:undefined}]}else if(isArray(filter)){objKeys=filter}else{var keys=Object.keys(obj);objKeys=sort?keys.sort(sort):keys}for(var j=0;j0?prefix+joined:""}},{"./formats":175,"./utils":179,"side-channel":198}],179:[function(require,module,exports){"use strict";var formats=require("./formats");var has=Object.prototype.hasOwnProperty;var isArray=Array.isArray;var hexTable=function(){var array=[];for(var i=0;i<256;++i){array.push("%"+((i<16?"0":"")+i.toString(16)).toUpperCase())}return array}();var compactQueue=function compactQueue(queue){while(queue.length>1){var item=queue.pop();var obj=item.obj[item.prop];if(isArray(obj)){var compacted=[];for(var j=0;j=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||format===formats.RFC1738&&(c===40||c===41)){out+=string.charAt(i);continue}if(c<128){out=out+hexTable[c];continue}if(c<2048){out=out+(hexTable[192|c>>6]+hexTable[128|c&63]);continue}if(c<55296||c>=57344){out=out+(hexTable[224|c>>12]+hexTable[128|c>>6&63]+hexTable[128|c&63]);continue}i+=1;c=65536+((c&1023)<<10|string.charCodeAt(i)&1023);out+=hexTable[240|c>>18]+hexTable[128|c>>12&63]+hexTable[128|c>>6&63]+hexTable[128|c&63]}return out};var compact=function compact(value){var queue=[{obj:{o:value},prop:"o"}];var refs=[];for(var i=0;i */ let promise;module.exports=typeof queueMicrotask==="function"?queueMicrotask.bind(typeof window!=="undefined"?window:global):cb=>(promise||(promise=Promise.resolve())).then(cb).catch((err=>setTimeout((()=>{throw err}),0)))}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],181:[function(require,module,exports){var inherits=require("inherits");var EventEmitter=require("events").EventEmitter;var now=require("right-now");var raf=require("raf");module.exports=Engine;function Engine(fn){if(!(this instanceof Engine))return new Engine(fn);this.running=false;this.last=now();this._frame=0;this._tick=this.tick.bind(this);if(fn)this.on("tick",fn)}inherits(Engine,EventEmitter);Engine.prototype.start=function(){if(this.running)return;this.running=true;this.last=now();this._frame=raf(this._tick);return this};Engine.prototype.stop=function(){this.running=false;if(this._frame!==0)raf.cancel(this._frame);this._frame=0;return this};Engine.prototype.tick=function(){this._frame=raf(this._tick);var time=now();var dt=time-this.last;this.emit("tick",dt);this.last=time}},{events:31,inherits:115,raf:182,"right-now":186}],182:[function(require,module,exports){(function(global){(function(){var now=require("performance-now"),root=typeof window==="undefined"?global:window,vendors=["moz","webkit"],suffix="AnimationFrame",raf=root["request"+suffix],caf=root["cancel"+suffix]||root["cancelRequest"+suffix];for(var i=0;!raf&&iMAX_UINT32)throw new RangeError("requested too many random bytes");var bytes=Buffer.allocUnsafe(size);if(size>0){if(size>MAX_BYTES){for(var generated=0;generated=0&&(value|0)===value)){raise("invalid parameter type, ("+value+")"+encolon(message)+". must be a nonnegative integer")}}function checkOneOf(value,list,message){if(list.indexOf(value)<0){raise("invalid value"+encolon(message)+". must be one of: "+list)}}var constructorKeys=["gl","canvas","container","attributes","pixelRatio","extensions","optionalExtensions","profile","onDone"];function checkConstructor(obj){Object.keys(obj).forEach((function(key){if(constructorKeys.indexOf(key)<0){raise('invalid regl constructor argument "'+key+'". must be one of '+constructorKeys)}}))}function leftPad(str,n){str=str+"";while(str.length0){result.push(new ShaderError("unknown",0,errMsg))}}));return result}function annotateFiles(files,errors){errors.forEach((function(error){var file=files[error.file];if(file){var line=file.index[error.line];if(line){line.errors.push(error);file.hasErrors=true;return}}files.unknown.hasErrors=true;files.unknown.lines[0].errors.push(error)}))}function checkShaderError(gl,shader,source,type,command){if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){var errLog=gl.getShaderInfoLog(shader);var typeName=type===gl.FRAGMENT_SHADER?"fragment":"vertex";checkCommandType(source,"string",typeName+" shader source must be a string",command);var files=parseSource(source,command);var errors=parseErrorLog(errLog);annotateFiles(files,errors);Object.keys(files).forEach((function(fileNumber){var file=files[fileNumber];if(!file.hasErrors){return}var strings=[""];var styles=[""];function push(str,style){strings.push(str);styles.push(style||"")}push("file number "+fileNumber+": "+file.name+"\n","color:red;text-decoration:underline;font-weight:bold");file.lines.forEach((function(line){if(line.errors.length>0){push(leftPad(line.number,4)+"| ","background-color:yellow; font-weight:bold");push(line.line+endl,"color:red; background-color:yellow; font-weight:bold");var offset=0;line.errors.forEach((function(error){var message=error.message;var token=/^\s*'(.*)'\s*:\s*(.*)$/.exec(message);if(token){var tokenPat=token[1];message=token[2];switch(tokenPat){case"assign":tokenPat="=";break}offset=Math.max(line.line.indexOf(tokenPat,offset),0)}else{offset=0}push(leftPad("| ",6));push(leftPad("^^^",offset+3)+endl,"font-weight:bold");push(leftPad("| ",6));push(message+endl,"font-weight:bold")}));push(leftPad("| ",6)+endl)}else{push(leftPad(line.number,4)+"| ");push(line.line+endl,"color:red")}}));if(typeof document!=="undefined"&&!window.chrome){styles[0]=strings.join("%c");console.log.apply(console,styles)}else{console.log(strings.join(""))}}));check.raise("Error compiling "+typeName+" shader, "+files[0].name)}}function checkLinkError(gl,program,fragShader,vertShader,command){if(!gl.getProgramParameter(program,gl.LINK_STATUS)){var errLog=gl.getProgramInfoLog(program);var fragParse=parseSource(fragShader,command);var vertParse=parseSource(vertShader,command);var header='Error linking program with vertex shader, "'+vertParse[0].name+'", and fragment shader "'+fragParse[0].name+'"';if(typeof document!=="undefined"){console.log("%c"+header+endl+"%c"+errLog,"color:red;text-decoration:underline;font-weight:bold","color:red")}else{console.log(header+endl+errLog)}check.raise(header)}}function saveCommandRef(object){object._commandRef=guessCommand()}function saveDrawCommandInfo(opts,uniforms,attributes,stringStore){saveCommandRef(opts);function id(str){if(str){return stringStore.id(str)}return 0}opts._fragId=id(opts.static.frag);opts._vertId=id(opts.static.vert);function addProps(dict,set){Object.keys(set).forEach((function(u){dict[stringStore.id(u)]=true}))}var uniformSet=opts._uniformSet={};addProps(uniformSet,uniforms.static);addProps(uniformSet,uniforms.dynamic);var attributeSet=opts._attributeSet={};addProps(attributeSet,attributes.static);addProps(attributeSet,attributes.dynamic);opts._hasCount="count"in opts.static||"count"in opts.dynamic||"elements"in opts.static||"elements"in opts.dynamic}function commandRaise(message,command){var callSite=guessCallSite();raise(message+" in command "+(command||guessCommand())+(callSite==="unknown"?"":" called from "+callSite))}function checkCommand(pred,message,command){if(!pred){commandRaise(message,command||guessCommand())}}function checkParameterCommand(param,possibilities,message,command){if(!(param in possibilities)){commandRaise("unknown parameter ("+param+")"+encolon(message)+". possible values: "+Object.keys(possibilities).join(),command||guessCommand())}}function checkCommandType(value,type,message,command){if(!standardTypeEh(value,type)){commandRaise("invalid parameter type"+encolon(message)+". expected "+type+", got "+typeof value,command||guessCommand())}}function checkOptional(block){block()}function checkFramebufferFormat(attachment,texFormats,rbFormats){if(attachment.texture){checkOneOf(attachment.texture._texture.internalformat,texFormats,"unsupported texture format for attachment")}else{checkOneOf(attachment.renderbuffer._renderbuffer.format,rbFormats,"unsupported renderbuffer format for attachment")}}var GL_CLAMP_TO_EDGE=33071;var GL_NEAREST=9728;var GL_NEAREST_MIPMAP_NEAREST=9984;var GL_LINEAR_MIPMAP_NEAREST=9985;var GL_NEAREST_MIPMAP_LINEAR=9986;var GL_LINEAR_MIPMAP_LINEAR=9987;var GL_BYTE=5120;var GL_UNSIGNED_BYTE=5121;var GL_SHORT=5122;var GL_UNSIGNED_SHORT=5123;var GL_INT=5124;var GL_UNSIGNED_INT=5125;var GL_FLOAT=5126;var GL_UNSIGNED_SHORT_4_4_4_4=32819;var GL_UNSIGNED_SHORT_5_5_5_1=32820;var GL_UNSIGNED_SHORT_5_6_5=33635;var GL_UNSIGNED_INT_24_8_WEBGL=34042;var GL_HALF_FLOAT_OES=36193;var TYPE_SIZE={};TYPE_SIZE[GL_BYTE]=TYPE_SIZE[GL_UNSIGNED_BYTE]=1;TYPE_SIZE[GL_SHORT]=TYPE_SIZE[GL_UNSIGNED_SHORT]=TYPE_SIZE[GL_HALF_FLOAT_OES]=TYPE_SIZE[GL_UNSIGNED_SHORT_5_6_5]=TYPE_SIZE[GL_UNSIGNED_SHORT_4_4_4_4]=TYPE_SIZE[GL_UNSIGNED_SHORT_5_5_5_1]=2;TYPE_SIZE[GL_INT]=TYPE_SIZE[GL_UNSIGNED_INT]=TYPE_SIZE[GL_FLOAT]=TYPE_SIZE[GL_UNSIGNED_INT_24_8_WEBGL]=4;function pixelSize(type,channels){if(type===GL_UNSIGNED_SHORT_5_5_5_1||type===GL_UNSIGNED_SHORT_4_4_4_4||type===GL_UNSIGNED_SHORT_5_6_5){return 2}else if(type===GL_UNSIGNED_INT_24_8_WEBGL){return 4}else{return TYPE_SIZE[type]*channels}}function isPow2(v){return!(v&v-1)&&!!v}function checkTexture2D(info,mipData,limits){var i;var w=mipData.width;var h=mipData.height;var c=mipData.channels;check(w>0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape");if(info.wrapS!==GL_CLAMP_TO_EDGE||info.wrapT!==GL_CLAMP_TO_EDGE){check(isPow2(w)&&isPow2(h),"incompatible wrap mode for texture, both width and height must be power of 2")}if(mipData.mipmask===1){if(w!==1&&h!==1){check(info.minFilter!==GL_NEAREST_MIPMAP_NEAREST&&info.minFilter!==GL_NEAREST_MIPMAP_LINEAR&&info.minFilter!==GL_LINEAR_MIPMAP_NEAREST&&info.minFilter!==GL_LINEAR_MIPMAP_LINEAR,"min filter requires mipmap")}}else{check(isPow2(w)&&isPow2(h),"texture must be a square power of 2 to support mipmapping");check(mipData.mipmask===(w<<1)-1,"missing or incomplete mipmap data")}if(mipData.type===GL_FLOAT){if(limits.extensions.indexOf("oes_texture_float_linear")<0){check(info.minFilter===GL_NEAREST&&info.magFilter===GL_NEAREST,"filter not supported, must enable oes_texture_float_linear")}check(!info.genMipmaps,"mipmap generation not supported with float textures")}var mipimages=mipData.images;for(i=0;i<16;++i){if(mipimages[i]){var mw=w>>i;var mh=h>>i;check(mipData.mipmask&1<0&&w<=limits.maxTextureSize&&h>0&&h<=limits.maxTextureSize,"invalid texture shape");check(w===h,"cube map must be square");check(info.wrapS===GL_CLAMP_TO_EDGE&&info.wrapT===GL_CLAMP_TO_EDGE,"wrap mode not supported by cube map");for(var i=0;i>j;var mh=h>>j;check(face.mipmask&1<1&&firstChar===lastChar&&(firstChar==='"'||firstChar==="'")){return['"'+escapeStr(str.substr(1,str.length-2))+'"']}var parts=/\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str);if(parts){return splitParts(str.substr(0,parts.index)).concat(splitParts(parts[1])).concat(splitParts(str.substr(parts.index+parts[0].length)))}var subparts=str.split(".");if(subparts.length===1){return['"'+escapeStr(str)+'"']}var result=[];for(var i=0;iunbox(y,path+"["+i+"]"))))}else if(x instanceof DynamicVariable){return x}check$1(false,"invalid option type in uniform "+path)}var dynamic={DynamicVariable:DynamicVariable,define:defineDynamic,isDynamic:isDynamic,unbox:unbox,accessor:toAccessorString};var raf={next:typeof requestAnimationFrame==="function"?function(cb){return requestAnimationFrame(cb)}:function(cb){return setTimeout(cb,16)},cancel:typeof cancelAnimationFrame==="function"?function(raf){return cancelAnimationFrame(raf)}:clearTimeout};var clock=typeof performance!=="undefined"&&performance.now?function(){return performance.now()}:function(){return+new Date};function createStringStore(){var stringIds={"":0};var stringValues=[""];return{id:function(str){var result=stringIds[str];if(result){return result}result=stringIds[str]=stringValues.length;stringValues.push(str);return result},str:function(id){return stringValues[id]}}}function createCanvas(element,onDone,pixelRatio){var canvas=document.createElement("canvas");extend(canvas.style,{border:0,margin:0,padding:0,top:0,left:0});element.appendChild(canvas);if(element===document.body){canvas.style.position="absolute";extend(element.style,{margin:0,padding:0})}function resize(){var w=window.innerWidth;var h=window.innerHeight;if(element!==document.body){var bounds=element.getBoundingClientRect();w=bounds.right-bounds.left;h=bounds.bottom-bounds.top}canvas.width=pixelRatio*w;canvas.height=pixelRatio*h;extend(canvas.style,{width:w+"px",height:h+"px"})}var resizeObserver;if(element!==document.body&&typeof ResizeObserver==="function"){resizeObserver=new ResizeObserver((function(){setTimeout(resize)}));resizeObserver.observe(element)}else{window.addEventListener("resize",resize,false)}function onDestroy(){if(resizeObserver){resizeObserver.disconnect()}else{window.removeEventListener("resize",resize)}element.removeChild(canvas)}resize();return{canvas:canvas,onDestroy:onDestroy}}function createContext(canvas,contextAttributes){function get(name){try{return canvas.getContext(name,contextAttributes)}catch(e){return null}}return get("webgl")||get("experimental-webgl")||get("webgl-experimental")}function isHTMLElement(obj){return typeof obj.nodeName==="string"&&typeof obj.appendChild==="function"&&typeof obj.getBoundingClientRect==="function"}function isWebGLContext(obj){return typeof obj.drawArrays==="function"||typeof obj.drawElements==="function"}function parseExtensions(input){if(typeof input==="string"){return input.split()}check$1(Array.isArray(input),"invalid extension array");return input}function getElement(desc){if(typeof desc==="string"){check$1(typeof document!=="undefined","not supported outside of DOM");return document.querySelector(desc)}return desc}function parseArgs(args_){var args=args_||{};var element,container,canvas,gl;var contextAttributes={};var extensions=[];var optionalExtensions=[];var pixelRatio=typeof window==="undefined"?1:window.devicePixelRatio;var profile=false;var onDone=function(err){if(err){check$1.raise(err)}};var onDestroy=function(){};if(typeof args==="string"){check$1(typeof document!=="undefined","selector queries only supported in DOM enviroments");element=document.querySelector(args);check$1(element,"invalid query string for element")}else if(typeof args==="object"){if(isHTMLElement(args)){element=args}else if(isWebGLContext(args)){gl=args;canvas=gl.canvas}else{check$1.constructor(args);if("gl"in args){gl=args.gl}else if("canvas"in args){canvas=getElement(args.canvas)}else if("container"in args){container=getElement(args.container)}if("attributes"in args){contextAttributes=args.attributes;check$1.type(contextAttributes,"object","invalid context attributes")}if("extensions"in args){extensions=parseExtensions(args.extensions)}if("optionalExtensions"in args){optionalExtensions=parseExtensions(args.optionalExtensions)}if("onDone"in args){check$1.type(args.onDone,"function","invalid or missing onDone callback");onDone=args.onDone}if("profile"in args){profile=!!args.profile}if("pixelRatio"in args){pixelRatio=+args.pixelRatio;check$1(pixelRatio>0,"invalid pixel ratio")}}}else{check$1.raise("invalid arguments to regl")}if(element){if(element.nodeName.toLowerCase()==="canvas"){canvas=element}else{container=element}}if(!gl){if(!canvas){check$1(typeof document!=="undefined","must manually specify webgl context outside of DOM environments");var result=createCanvas(container||document.body,onDone,pixelRatio);if(!result){return null}canvas=result.canvas;onDestroy=result.onDestroy}if(contextAttributes.premultipliedAlpha===undefined)contextAttributes.premultipliedAlpha=true;gl=createContext(canvas,contextAttributes)}if(!gl){onDestroy();onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org");return null}return{gl:gl,canvas:canvas,container:container,extensions:extensions,optionalExtensions:optionalExtensions,pixelRatio:pixelRatio,profile:profile,onDone:onDone,onDestroy:onDestroy}}function createExtensionCache(gl,config){var extensions={};function tryLoadExtension(name_){check$1.type(name_,"string","extension name must be string");var name=name_.toLowerCase();var ext;try{ext=extensions[name]=gl.getExtension(name)}catch(e){}return!!ext}for(var i=0;i65535)<<4;v>>>=r;shift=(v>255)<<3;v>>>=shift;r|=shift;shift=(v>15)<<2;v>>>=shift;r|=shift;shift=(v>3)<<1;v>>>=shift;r|=shift;return r|v>>1}function createPool(){var bufferPool=loop(8,(function(){return[]}));function alloc(n){var sz=nextPow16(n);var bin=bufferPool[log2(sz)>>2];if(bin.length>0){return bin.pop()}return new ArrayBuffer(sz)}function free(buf){bufferPool[log2(buf.byteLength)>>2].push(buf)}function allocType(type,n){var result=null;switch(type){case GL_BYTE$1:result=new Int8Array(alloc(n),0,n);break;case GL_UNSIGNED_BYTE$2:result=new Uint8Array(alloc(n),0,n);break;case GL_SHORT$1:result=new Int16Array(alloc(2*n),0,n);break;case GL_UNSIGNED_SHORT$1:result=new Uint16Array(alloc(2*n),0,n);break;case GL_INT$1:result=new Int32Array(alloc(4*n),0,n);break;case GL_UNSIGNED_INT$1:result=new Uint32Array(alloc(4*n),0,n);break;case GL_FLOAT$2:result=new Float32Array(alloc(4*n),0,n);break;default:return null}if(result.length!==n){return result.subarray(0,n)}return result}function freeType(array){free(array.buffer)}return{alloc:alloc,free:free,allocType:allocType,freeType:freeType}}var pool=createPool();pool.zero=createPool();var GL_SUBPIXEL_BITS=3408;var GL_RED_BITS=3410;var GL_GREEN_BITS=3411;var GL_BLUE_BITS=3412;var GL_ALPHA_BITS=3413;var GL_DEPTH_BITS=3414;var GL_STENCIL_BITS=3415;var GL_ALIASED_POINT_SIZE_RANGE=33901;var GL_ALIASED_LINE_WIDTH_RANGE=33902;var GL_MAX_TEXTURE_SIZE=3379;var GL_MAX_VIEWPORT_DIMS=3386;var GL_MAX_VERTEX_ATTRIBS=34921;var GL_MAX_VERTEX_UNIFORM_VECTORS=36347;var GL_MAX_VARYING_VECTORS=36348;var GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS=35661;var GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS=35660;var GL_MAX_TEXTURE_IMAGE_UNITS=34930;var GL_MAX_FRAGMENT_UNIFORM_VECTORS=36349;var GL_MAX_CUBE_MAP_TEXTURE_SIZE=34076;var GL_MAX_RENDERBUFFER_SIZE=34024;var GL_VENDOR=7936;var GL_RENDERER=7937;var GL_VERSION=7938;var GL_SHADING_LANGUAGE_VERSION=35724;var GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT=34047;var GL_MAX_COLOR_ATTACHMENTS_WEBGL=36063;var GL_MAX_DRAW_BUFFERS_WEBGL=34852;var GL_TEXTURE_2D=3553;var GL_TEXTURE_CUBE_MAP=34067;var GL_TEXTURE_CUBE_MAP_POSITIVE_X=34069;var GL_TEXTURE0=33984;var GL_RGBA=6408;var GL_FLOAT$1=5126;var GL_UNSIGNED_BYTE$1=5121;var GL_FRAMEBUFFER=36160;var GL_FRAMEBUFFER_COMPLETE=36053;var GL_COLOR_ATTACHMENT0=36064;var GL_COLOR_BUFFER_BIT$1=16384;var wrapLimits=function(gl,extensions){var maxAnisotropic=1;if(extensions.ext_texture_filter_anisotropic){maxAnisotropic=gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)}var maxDrawbuffers=1;var maxColorAttachments=1;if(extensions.webgl_draw_buffers){maxDrawbuffers=gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL);maxColorAttachments=gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL)}var readFloat=!!extensions.oes_texture_float;if(readFloat){var readFloatTexture=gl.createTexture();gl.bindTexture(GL_TEXTURE_2D,readFloatTexture);gl.texImage2D(GL_TEXTURE_2D,0,GL_RGBA,1,1,0,GL_RGBA,GL_FLOAT$1,null);var fbo=gl.createFramebuffer();gl.bindFramebuffer(GL_FRAMEBUFFER,fbo);gl.framebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,readFloatTexture,0);gl.bindTexture(GL_TEXTURE_2D,null);if(gl.checkFramebufferStatus(GL_FRAMEBUFFER)!==GL_FRAMEBUFFER_COMPLETE)readFloat=false;else{gl.viewport(0,0,1,1);gl.clearColor(1,0,0,1);gl.clear(GL_COLOR_BUFFER_BIT$1);var pixels=pool.allocType(GL_FLOAT$1,4);gl.readPixels(0,0,1,1,GL_RGBA,GL_FLOAT$1,pixels);if(gl.getError())readFloat=false;else{gl.deleteFramebuffer(fbo);gl.deleteTexture(readFloatTexture);readFloat=pixels[0]===1}pool.freeType(pixels)}}var isIE=typeof navigator!=="undefined"&&(/MSIE/.test(navigator.userAgent)||/Trident\//.test(navigator.appVersion)||/Edge/.test(navigator.userAgent));var npotTextureCube=true;if(!isIE){var cubeTexture=gl.createTexture();var data=pool.allocType(GL_UNSIGNED_BYTE$1,36);gl.activeTexture(GL_TEXTURE0);gl.bindTexture(GL_TEXTURE_CUBE_MAP,cubeTexture);gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X,0,GL_RGBA,3,3,0,GL_RGBA,GL_UNSIGNED_BYTE$1,data);pool.freeType(data);gl.bindTexture(GL_TEXTURE_CUBE_MAP,null);gl.deleteTexture(cubeTexture);npotTextureCube=!gl.getError()}return{colorBits:[gl.getParameter(GL_RED_BITS),gl.getParameter(GL_GREEN_BITS),gl.getParameter(GL_BLUE_BITS),gl.getParameter(GL_ALPHA_BITS)],depthBits:gl.getParameter(GL_DEPTH_BITS),stencilBits:gl.getParameter(GL_STENCIL_BITS),subpixelBits:gl.getParameter(GL_SUBPIXEL_BITS),extensions:Object.keys(extensions).filter((function(ext){return!!extensions[ext]})),maxAnisotropic:maxAnisotropic,maxDrawbuffers:maxDrawbuffers,maxColorAttachments:maxColorAttachments,pointSizeDims:gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE),lineWidthDims:gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE),maxViewportDims:gl.getParameter(GL_MAX_VIEWPORT_DIMS),maxCombinedTextureUnits:gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS),maxCubeMapSize:gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE),maxRenderbufferSize:gl.getParameter(GL_MAX_RENDERBUFFER_SIZE),maxTextureUnits:gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS),maxTextureSize:gl.getParameter(GL_MAX_TEXTURE_SIZE),maxAttributes:gl.getParameter(GL_MAX_VERTEX_ATTRIBS),maxVertexUniforms:gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS),maxVertexTextureUnits:gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS),maxVaryingVectors:gl.getParameter(GL_MAX_VARYING_VECTORS),maxFragmentUniforms:gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS),glsl:gl.getParameter(GL_SHADING_LANGUAGE_VERSION),renderer:gl.getParameter(GL_RENDERER),vendor:gl.getParameter(GL_VENDOR),version:gl.getParameter(GL_VERSION),readFloat:readFloat,npotTextureCube:npotTextureCube}};function isNDArrayLike(obj){return!!obj&&typeof obj==="object"&&Array.isArray(obj.shape)&&Array.isArray(obj.stride)&&typeof obj.offset==="number"&&obj.shape.length===obj.stride.length&&(Array.isArray(obj.data)||isTypedArray(obj.data))}var values=function(obj){return Object.keys(obj).map((function(key){return obj[key]}))};var flattenUtils={shape:arrayShape$1,flatten:flattenArray};function flatten1D(array,nx,out){for(var i=0;i0){var flatData;if(Array.isArray(data[0])){shape=arrayShape(data);var dim=1;for(var i=1;i0){if(typeof data[0]==="number"){var converted=pool.allocType(buffer.dtype,data.length);copyArray(converted,data);setSubData(converted,offset);pool.freeType(converted)}else if(Array.isArray(data[0])||isTypedArray(data[0])){shape=arrayShape(data);var flatData=arrayFlatten(data,shape,buffer.dtype);setSubData(flatData,offset);pool.freeType(flatData)}else{check$1.raise("invalid buffer data")}}}else if(isNDArrayLike(data)){shape=data.shape;var stride=data.stride;var shapeX=0;var shapeY=0;var strideX=0;var strideY=0;if(shape.length===1){shapeX=shape[0];shapeY=1;strideX=stride[0];strideY=0}else if(shape.length===2){shapeX=shape[0];shapeY=shape[1];strideX=stride[0];strideY=stride[1]}else{check$1.raise("invalid shape")}var dtype=Array.isArray(data.data)?buffer.dtype:typedArrayCode(data.data);var transposeData=pool.allocType(dtype,shapeX*shapeY);transpose(transposeData,data.data,shapeX,shapeY,strideX,strideY,data.offset);setSubData(transposeData,offset);pool.freeType(transposeData)}else{check$1.raise("invalid data for buffer subdata")}return reglBuffer}if(!deferInit){reglBuffer(options)}reglBuffer._reglType="buffer";reglBuffer._buffer=buffer;reglBuffer.subdata=subdata;if(config.profile){reglBuffer.stats=buffer.stats}reglBuffer.destroy=function(){destroy(buffer)};return reglBuffer}function restoreBuffers(){values(bufferSet).forEach((function(buffer){buffer.buffer=gl.createBuffer();gl.bindBuffer(buffer.type,buffer.buffer);gl.bufferData(buffer.type,buffer.persistentData||buffer.byteLength,buffer.usage)}))}if(config.profile){stats.getTotalBufferSize=function(){var total=0;Object.keys(bufferSet).forEach((function(key){total+=bufferSet[key].stats.size}));return total}}return{create:createBuffer,createStream:createStream,destroyStream:destroyStream,clear:function(){values(bufferSet).forEach(destroy);streamPool.forEach(destroy)},getBuffer:function(wrapper){if(wrapper&&wrapper._buffer instanceof REGLBuffer){return wrapper._buffer}return null},restore:restoreBuffers,_initBuffer:initBufferFromData}}var points=0;var point=0;var lines=1;var line=1;var triangles=4;var triangle=4;var primTypes={points:points,point:point,lines:lines,line:line,triangles:triangles,triangle:triangle,"line loop":2,"line strip":3,"triangle strip":5,"triangle fan":6};var GL_POINTS=0;var GL_LINES=1;var GL_TRIANGLES=4;var GL_BYTE$2=5120;var GL_UNSIGNED_BYTE$4=5121;var GL_SHORT$2=5122;var GL_UNSIGNED_SHORT$2=5123;var GL_INT$2=5124;var GL_UNSIGNED_INT$2=5125;var GL_ELEMENT_ARRAY_BUFFER=34963;var GL_STREAM_DRAW$1=35040;var GL_STATIC_DRAW$1=35044;function wrapElementsState(gl,extensions,bufferState,stats){var elementSet={};var elementCount=0;var elementTypes={uint8:GL_UNSIGNED_BYTE$4,uint16:GL_UNSIGNED_SHORT$2};if(extensions.oes_element_index_uint){elementTypes.uint32=GL_UNSIGNED_INT$2}function REGLElementBuffer(buffer){this.id=elementCount++;elementSet[this.id]=this;this.buffer=buffer;this.primType=GL_TRIANGLES;this.vertCount=0;this.type=0}REGLElementBuffer.prototype.bind=function(){this.buffer.bind()};var bufferPool=[];function createElementStream(data){var result=bufferPool.pop();if(!result){result=new REGLElementBuffer(bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,true,false)._buffer)}initElements(result,data,GL_STREAM_DRAW$1,-1,-1,0,0);return result}function destroyElementStream(elements){bufferPool.push(elements)}function initElements(elements,data,usage,prim,count,byteLength,type){elements.buffer.bind();var dtype;if(data){var predictedType=type;if(!type&&(!isTypedArray(data)||isNDArrayLike(data)&&!isTypedArray(data.data))){predictedType=extensions.oes_element_index_uint?GL_UNSIGNED_INT$2:GL_UNSIGNED_SHORT$2}bufferState._initBuffer(elements.buffer,data,usage,predictedType,3)}else{gl.bufferData(GL_ELEMENT_ARRAY_BUFFER,byteLength,usage);elements.buffer.dtype=dtype||GL_UNSIGNED_BYTE$4;elements.buffer.usage=usage;elements.buffer.dimension=3;elements.buffer.byteLength=byteLength}dtype=type;if(!type){switch(elements.buffer.dtype){case GL_UNSIGNED_BYTE$4:case GL_BYTE$2:dtype=GL_UNSIGNED_BYTE$4;break;case GL_UNSIGNED_SHORT$2:case GL_SHORT$2:dtype=GL_UNSIGNED_SHORT$2;break;case GL_UNSIGNED_INT$2:case GL_INT$2:dtype=GL_UNSIGNED_INT$2;break;default:check$1.raise("unsupported type for element array")}elements.buffer.dtype=dtype}elements.type=dtype;check$1(dtype!==GL_UNSIGNED_INT$2||!!extensions.oes_element_index_uint,"32 bit element buffers not supported, enable oes_element_index_uint first");var vertCount=count;if(vertCount<0){vertCount=elements.buffer.byteLength;if(dtype===GL_UNSIGNED_SHORT$2){vertCount>>=1}else if(dtype===GL_UNSIGNED_INT$2){vertCount>>=2}}elements.vertCount=vertCount;var primType=prim;if(prim<0){primType=GL_TRIANGLES;var dimension=elements.buffer.dimension;if(dimension===1)primType=GL_POINTS;if(dimension===2)primType=GL_LINES;if(dimension===3)primType=GL_TRIANGLES}elements.primType=primType}function destroyElements(elements){stats.elementsCount--;check$1(elements.buffer!==null,"must not double destroy elements");delete elementSet[elements.id];elements.buffer.destroy();elements.buffer=null}function createElements(options,persistent){var buffer=bufferState.create(null,GL_ELEMENT_ARRAY_BUFFER,true);var elements=new REGLElementBuffer(buffer._buffer);stats.elementsCount++;function reglElements(options){if(!options){buffer();elements.primType=GL_TRIANGLES;elements.vertCount=0;elements.type=GL_UNSIGNED_BYTE$4}else if(typeof options==="number"){buffer(options);elements.primType=GL_TRIANGLES;elements.vertCount=options|0;elements.type=GL_UNSIGNED_BYTE$4}else{var data=null;var usage=GL_STATIC_DRAW$1;var primType=-1;var vertCount=-1;var byteLength=0;var dtype=0;if(Array.isArray(options)||isTypedArray(options)||isNDArrayLike(options)){data=options}else{check$1.type(options,"object","invalid arguments for elements");if("data"in options){data=options.data;check$1(Array.isArray(data)||isTypedArray(data)||isNDArrayLike(data),"invalid data for element buffer")}if("usage"in options){check$1.parameter(options.usage,usageTypes,"invalid element buffer usage");usage=usageTypes[options.usage]}if("primitive"in options){check$1.parameter(options.primitive,primTypes,"invalid element buffer primitive");primType=primTypes[options.primitive]}if("count"in options){check$1(typeof options.count==="number"&&options.count>=0,"invalid vertex count for elements");vertCount=options.count|0}if("type"in options){check$1.parameter(options.type,elementTypes,"invalid buffer type");dtype=elementTypes[options.type]}if("length"in options){byteLength=options.length|0}else{byteLength=vertCount;if(dtype===GL_UNSIGNED_SHORT$2||dtype===GL_SHORT$2){byteLength*=2}else if(dtype===GL_UNSIGNED_INT$2||dtype===GL_INT$2){byteLength*=4}}}initElements(elements,data,usage,primType,vertCount,byteLength,dtype)}return reglElements}reglElements(options);reglElements._reglType="elements";reglElements._elements=elements;reglElements.subdata=function(data,offset){buffer.subdata(data,offset);return reglElements};reglElements.destroy=function(){destroyElements(elements)};return reglElements}return{create:createElements,createStream:createElementStream,destroyStream:destroyElementStream,getElements:function(elements){if(typeof elements==="function"&&elements._elements instanceof REGLElementBuffer){return elements._elements}return null},clear:function(){values(elementSet).forEach(destroyElements)}}}var FLOAT=new Float32Array(1);var INT=new Uint32Array(FLOAT.buffer);var GL_UNSIGNED_SHORT$4=5123;function convertToHalfFloat(array){var ushorts=pool.allocType(GL_UNSIGNED_SHORT$4,array.length);for(var i=0;i>>31<<15;var exp=(x<<1>>>24)-127;var frac=x>>13&(1<<10)-1;if(exp<-24){ushorts[i]=sgn}else if(exp<-14){var s=-14-exp;ushorts[i]=sgn+(frac+(1<<10)>>s)}else if(exp>15){ushorts[i]=sgn+31744}else{ushorts[i]=sgn+(exp+15<<10)+frac}}}return ushorts}function isArrayLike(s){return Array.isArray(s)||isTypedArray(s)}var isPow2$1=function(v){return!(v&v-1)&&!!v};var GL_COMPRESSED_TEXTURE_FORMATS=34467;var GL_TEXTURE_2D$1=3553;var GL_TEXTURE_CUBE_MAP$1=34067;var GL_TEXTURE_CUBE_MAP_POSITIVE_X$1=34069;var GL_RGBA$1=6408;var GL_ALPHA=6406;var GL_RGB=6407;var GL_LUMINANCE=6409;var GL_LUMINANCE_ALPHA=6410;var GL_RGBA4=32854;var GL_RGB5_A1=32855;var GL_RGB565=36194;var GL_UNSIGNED_SHORT_4_4_4_4$1=32819;var GL_UNSIGNED_SHORT_5_5_5_1$1=32820;var GL_UNSIGNED_SHORT_5_6_5$1=33635;var GL_UNSIGNED_INT_24_8_WEBGL$1=34042;var GL_DEPTH_COMPONENT=6402;var GL_DEPTH_STENCIL=34041;var GL_SRGB_EXT=35904;var GL_SRGB_ALPHA_EXT=35906;var GL_HALF_FLOAT_OES$1=36193;var GL_COMPRESSED_RGB_S3TC_DXT1_EXT=33776;var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT=33777;var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT=33778;var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT=33779;var GL_COMPRESSED_RGB_ATC_WEBGL=35986;var GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=35987;var GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=34798;var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG=35840;var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG=35841;var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=35842;var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=35843;var GL_COMPRESSED_RGB_ETC1_WEBGL=36196;var GL_UNSIGNED_BYTE$5=5121;var GL_UNSIGNED_SHORT$3=5123;var GL_UNSIGNED_INT$3=5125;var GL_FLOAT$4=5126;var GL_TEXTURE_WRAP_S=10242;var GL_TEXTURE_WRAP_T=10243;var GL_REPEAT=10497;var GL_CLAMP_TO_EDGE$1=33071;var GL_MIRRORED_REPEAT=33648;var GL_TEXTURE_MAG_FILTER=10240;var GL_TEXTURE_MIN_FILTER=10241;var GL_NEAREST$1=9728;var GL_LINEAR=9729;var GL_NEAREST_MIPMAP_NEAREST$1=9984;var GL_LINEAR_MIPMAP_NEAREST$1=9985;var GL_NEAREST_MIPMAP_LINEAR$1=9986;var GL_LINEAR_MIPMAP_LINEAR$1=9987;var GL_GENERATE_MIPMAP_HINT=33170;var GL_DONT_CARE=4352;var GL_FASTEST=4353;var GL_NICEST=4354;var GL_TEXTURE_MAX_ANISOTROPY_EXT=34046;var GL_UNPACK_ALIGNMENT=3317;var GL_UNPACK_FLIP_Y_WEBGL=37440;var GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL=37441;var GL_UNPACK_COLORSPACE_CONVERSION_WEBGL=37443;var GL_BROWSER_DEFAULT_WEBGL=37444;var GL_TEXTURE0$1=33984;var MIPMAP_FILTERS=[GL_NEAREST_MIPMAP_NEAREST$1,GL_NEAREST_MIPMAP_LINEAR$1,GL_LINEAR_MIPMAP_NEAREST$1,GL_LINEAR_MIPMAP_LINEAR$1];var CHANNELS_FORMAT=[0,GL_LUMINANCE,GL_LUMINANCE_ALPHA,GL_RGB,GL_RGBA$1];var FORMAT_CHANNELS={};FORMAT_CHANNELS[GL_LUMINANCE]=FORMAT_CHANNELS[GL_ALPHA]=FORMAT_CHANNELS[GL_DEPTH_COMPONENT]=1;FORMAT_CHANNELS[GL_DEPTH_STENCIL]=FORMAT_CHANNELS[GL_LUMINANCE_ALPHA]=2;FORMAT_CHANNELS[GL_RGB]=FORMAT_CHANNELS[GL_SRGB_EXT]=3;FORMAT_CHANNELS[GL_RGBA$1]=FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT]=4;function objectName(str){return"[object "+str+"]"}var CANVAS_CLASS=objectName("HTMLCanvasElement");var OFFSCREENCANVAS_CLASS=objectName("OffscreenCanvas");var CONTEXT2D_CLASS=objectName("CanvasRenderingContext2D");var BITMAP_CLASS=objectName("ImageBitmap");var IMAGE_CLASS=objectName("HTMLImageElement");var VIDEO_CLASS=objectName("HTMLVideoElement");var PIXEL_CLASSES=Object.keys(arrayTypes).concat([CANVAS_CLASS,OFFSCREENCANVAS_CLASS,CONTEXT2D_CLASS,BITMAP_CLASS,IMAGE_CLASS,VIDEO_CLASS]);var TYPE_SIZES=[];TYPE_SIZES[GL_UNSIGNED_BYTE$5]=1;TYPE_SIZES[GL_FLOAT$4]=4;TYPE_SIZES[GL_HALF_FLOAT_OES$1]=2;TYPE_SIZES[GL_UNSIGNED_SHORT$3]=2;TYPE_SIZES[GL_UNSIGNED_INT$3]=4;var FORMAT_SIZES_SPECIAL=[];FORMAT_SIZES_SPECIAL[GL_RGBA4]=2;FORMAT_SIZES_SPECIAL[GL_RGB5_A1]=2;FORMAT_SIZES_SPECIAL[GL_RGB565]=2;FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL]=4;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT]=.5;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT]=.5;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT]=1;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT]=1;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL]=.5;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL]=1;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL]=1;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG]=.5;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG]=.25;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG]=.5;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG]=.25;FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL]=.5;function isNumericArray(arr){return Array.isArray(arr)&&(arr.length===0||typeof arr[0]==="number")}function isRectArray(arr){if(!Array.isArray(arr)){return false}var width=arr.length;if(width===0||!isArrayLike(arr[0])){return false}return true}function classString(x){return Object.prototype.toString.call(x)}function isCanvasElement(object){return classString(object)===CANVAS_CLASS}function isOffscreenCanvas(object){return classString(object)===OFFSCREENCANVAS_CLASS}function isContext2D(object){return classString(object)===CONTEXT2D_CLASS}function isBitmap(object){return classString(object)===BITMAP_CLASS}function isImageElement(object){return classString(object)===IMAGE_CLASS}function isVideoElement(object){return classString(object)===VIDEO_CLASS}function isPixelData(object){if(!object){return false}var className=classString(object);if(PIXEL_CLASSES.indexOf(className)>=0){return true}return isNumericArray(object)||isRectArray(object)||isNDArrayLike(object)}function typedArrayCode$1(data){return arrayTypes[Object.prototype.toString.call(data)]|0}function convertData(result,data){var n=data.length;switch(result.type){case GL_UNSIGNED_BYTE$5:case GL_UNSIGNED_SHORT$3:case GL_UNSIGNED_INT$3:case GL_FLOAT$4:var converted=pool.allocType(result.type,n);converted.set(data);result.data=converted;break;case GL_HALF_FLOAT_OES$1:result.data=convertToHalfFloat(data);break;default:check$1.raise("unsupported texture type, must specify a typed array")}}function preConvert(image,n){return pool.allocType(image.type===GL_HALF_FLOAT_OES$1?GL_FLOAT$4:image.type,n)}function postConvert(image,data){if(image.type===GL_HALF_FLOAT_OES$1){image.data=convertToHalfFloat(data);pool.freeType(data)}else{image.data=data}}function transposeData(image,array,strideX,strideY,strideC,offset){var w=image.width;var h=image.height;var c=image.channels;var n=w*h*c;var data=preConvert(image,n);var p=0;for(var i=0;i=1){total+=s*w*w;w/=2}return total}else{return s*width*height}}function createTextureSet(gl,extensions,limits,reglPoll,contextState,stats,config){var mipmapHint={"don't care":GL_DONT_CARE,"dont care":GL_DONT_CARE,nice:GL_NICEST,fast:GL_FASTEST};var wrapModes={repeat:GL_REPEAT,clamp:GL_CLAMP_TO_EDGE$1,mirror:GL_MIRRORED_REPEAT};var magFilters={nearest:GL_NEAREST$1,linear:GL_LINEAR};var minFilters=extend({mipmap:GL_LINEAR_MIPMAP_LINEAR$1,"nearest mipmap nearest":GL_NEAREST_MIPMAP_NEAREST$1,"linear mipmap nearest":GL_LINEAR_MIPMAP_NEAREST$1,"nearest mipmap linear":GL_NEAREST_MIPMAP_LINEAR$1,"linear mipmap linear":GL_LINEAR_MIPMAP_LINEAR$1},magFilters);var colorSpace={none:0,browser:GL_BROWSER_DEFAULT_WEBGL};var textureTypes={uint8:GL_UNSIGNED_BYTE$5,rgba4:GL_UNSIGNED_SHORT_4_4_4_4$1,rgb565:GL_UNSIGNED_SHORT_5_6_5$1,"rgb5 a1":GL_UNSIGNED_SHORT_5_5_5_1$1};var textureFormats={alpha:GL_ALPHA,luminance:GL_LUMINANCE,"luminance alpha":GL_LUMINANCE_ALPHA,rgb:GL_RGB,rgba:GL_RGBA$1,rgba4:GL_RGBA4,"rgb5 a1":GL_RGB5_A1,rgb565:GL_RGB565};var compressedTextureFormats={};if(extensions.ext_srgb){textureFormats.srgb=GL_SRGB_EXT;textureFormats.srgba=GL_SRGB_ALPHA_EXT}if(extensions.oes_texture_float){textureTypes.float32=textureTypes.float=GL_FLOAT$4}if(extensions.oes_texture_half_float){textureTypes["float16"]=textureTypes["half float"]=GL_HALF_FLOAT_OES$1}if(extensions.webgl_depth_texture){extend(textureFormats,{depth:GL_DEPTH_COMPONENT,"depth stencil":GL_DEPTH_STENCIL});extend(textureTypes,{uint16:GL_UNSIGNED_SHORT$3,uint32:GL_UNSIGNED_INT$3,"depth stencil":GL_UNSIGNED_INT_24_8_WEBGL$1})}if(extensions.webgl_compressed_texture_s3tc){extend(compressedTextureFormats,{"rgb s3tc dxt1":GL_COMPRESSED_RGB_S3TC_DXT1_EXT,"rgba s3tc dxt1":GL_COMPRESSED_RGBA_S3TC_DXT1_EXT,"rgba s3tc dxt3":GL_COMPRESSED_RGBA_S3TC_DXT3_EXT,"rgba s3tc dxt5":GL_COMPRESSED_RGBA_S3TC_DXT5_EXT})}if(extensions.webgl_compressed_texture_atc){extend(compressedTextureFormats,{"rgb atc":GL_COMPRESSED_RGB_ATC_WEBGL,"rgba atc explicit alpha":GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL,"rgba atc interpolated alpha":GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL})}if(extensions.webgl_compressed_texture_pvrtc){extend(compressedTextureFormats,{"rgb pvrtc 4bppv1":GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG,"rgb pvrtc 2bppv1":GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG,"rgba pvrtc 4bppv1":GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG,"rgba pvrtc 2bppv1":GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG})}if(extensions.webgl_compressed_texture_etc1){compressedTextureFormats["rgb etc1"]=GL_COMPRESSED_RGB_ETC1_WEBGL}var supportedCompressedFormats=Array.prototype.slice.call(gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS));Object.keys(compressedTextureFormats).forEach((function(name){var format=compressedTextureFormats[name];if(supportedCompressedFormats.indexOf(format)>=0){textureFormats[name]=format}}));var supportedFormats=Object.keys(textureFormats);limits.textureFormats=supportedFormats;var textureFormatsInvert=[];Object.keys(textureFormats).forEach((function(key){var val=textureFormats[key];textureFormatsInvert[val]=key}));var textureTypesInvert=[];Object.keys(textureTypes).forEach((function(key){var val=textureTypes[key];textureTypesInvert[val]=key}));var magFiltersInvert=[];Object.keys(magFilters).forEach((function(key){var val=magFilters[key];magFiltersInvert[val]=key}));var minFiltersInvert=[];Object.keys(minFilters).forEach((function(key){var val=minFilters[key];minFiltersInvert[val]=key}));var wrapModesInvert=[];Object.keys(wrapModes).forEach((function(key){var val=wrapModes[key];wrapModesInvert[val]=key}));var colorFormats=supportedFormats.reduce((function(color,key){var glenum=textureFormats[key];if(glenum===GL_LUMINANCE||glenum===GL_ALPHA||glenum===GL_LUMINANCE||glenum===GL_LUMINANCE_ALPHA||glenum===GL_DEPTH_COMPONENT||glenum===GL_DEPTH_STENCIL||extensions.ext_srgb&&(glenum===GL_SRGB_EXT||glenum===GL_SRGB_ALPHA_EXT)){color[glenum]=glenum}else if(glenum===GL_RGB5_A1||key.indexOf("rgba")>=0){color[glenum]=GL_RGBA$1}else{color[glenum]=GL_RGB}return color}),{});function TexFlags(){this.internalformat=GL_RGBA$1;this.format=GL_RGBA$1;this.type=GL_UNSIGNED_BYTE$5;this.compressed=false;this.premultiplyAlpha=false;this.flipY=false;this.unpackAlignment=1;this.colorSpace=GL_BROWSER_DEFAULT_WEBGL;this.width=0;this.height=0;this.channels=0}function copyFlags(result,other){result.internalformat=other.internalformat;result.format=other.format;result.type=other.type;result.compressed=other.compressed;result.premultiplyAlpha=other.premultiplyAlpha;result.flipY=other.flipY;result.unpackAlignment=other.unpackAlignment;result.colorSpace=other.colorSpace;result.width=other.width;result.height=other.height;result.channels=other.channels}function parseFlags(flags,options){if(typeof options!=="object"||!options){return}if("premultiplyAlpha"in options){check$1.type(options.premultiplyAlpha,"boolean","invalid premultiplyAlpha");flags.premultiplyAlpha=options.premultiplyAlpha}if("flipY"in options){check$1.type(options.flipY,"boolean","invalid texture flip");flags.flipY=options.flipY}if("alignment"in options){check$1.oneOf(options.alignment,[1,2,4,8],"invalid texture unpack alignment");flags.unpackAlignment=options.alignment}if("colorSpace"in options){check$1.parameter(options.colorSpace,colorSpace,"invalid colorSpace");flags.colorSpace=colorSpace[options.colorSpace]}if("type"in options){var type=options.type;check$1(extensions.oes_texture_float||!(type==="float"||type==="float32"),"you must enable the OES_texture_float extension in order to use floating point textures.");check$1(extensions.oes_texture_half_float||!(type==="half float"||type==="float16"),"you must enable the OES_texture_half_float extension in order to use 16-bit floating point textures.");check$1(extensions.webgl_depth_texture||!(type==="uint16"||type==="uint32"||type==="depth stencil"),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures.");check$1.parameter(type,textureTypes,"invalid texture type");flags.type=textureTypes[type]}var w=flags.width;var h=flags.height;var c=flags.channels;var hasChannels=false;if("shape"in options){check$1(Array.isArray(options.shape)&&options.shape.length>=2,"shape must be an array");w=options.shape[0];h=options.shape[1];if(options.shape.length===3){c=options.shape[2];check$1(c>0&&c<=4,"invalid number of channels");hasChannels=true}check$1(w>=0&&w<=limits.maxTextureSize,"invalid width");check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")}else{if("radius"in options){w=h=options.radius;check$1(w>=0&&w<=limits.maxTextureSize,"invalid radius")}if("width"in options){w=options.width;check$1(w>=0&&w<=limits.maxTextureSize,"invalid width")}if("height"in options){h=options.height;check$1(h>=0&&h<=limits.maxTextureSize,"invalid height")}if("channels"in options){c=options.channels;check$1(c>0&&c<=4,"invalid number of channels");hasChannels=true}}flags.width=w|0;flags.height=h|0;flags.channels=c|0;var hasFormat=false;if("format"in options){var formatStr=options.format;check$1(extensions.webgl_depth_texture||!(formatStr==="depth"||formatStr==="depth stencil"),"you must enable the WEBGL_depth_texture extension in order to use depth/stencil textures.");check$1.parameter(formatStr,textureFormats,"invalid texture format");var internalformat=flags.internalformat=textureFormats[formatStr];flags.format=colorFormats[internalformat];if(formatStr in textureTypes){if(!("type"in options)){flags.type=textureTypes[formatStr]}}if(formatStr in compressedTextureFormats){flags.compressed=true}hasFormat=true}if(!hasChannels&&hasFormat){flags.channels=FORMAT_CHANNELS[flags.format]}else if(hasChannels&&!hasFormat){if(flags.channels!==CHANNELS_FORMAT[flags.format]){flags.format=flags.internalformat=CHANNELS_FORMAT[flags.channels]}}else if(hasFormat&&hasChannels){check$1(flags.channels===FORMAT_CHANNELS[flags.format],"number of channels inconsistent with specified format")}}function setFlags(flags){gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL,flags.flipY);gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL,flags.premultiplyAlpha);gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL,flags.colorSpace);gl.pixelStorei(GL_UNPACK_ALIGNMENT,flags.unpackAlignment)}function TexImage(){TexFlags.call(this);this.xOffset=0;this.yOffset=0;this.data=null;this.needsFree=false;this.element=null;this.needsCopy=false}function parseImage(image,options){var data=null;if(isPixelData(options)){data=options}else if(options){check$1.type(options,"object","invalid pixel data type");parseFlags(image,options);if("x"in options){image.xOffset=options.x|0}if("y"in options){image.yOffset=options.y|0}if(isPixelData(options.data)){data=options.data}}check$1(!image.compressed||data instanceof Uint8Array,"compressed texture data must be stored in a uint8array");if(options.copy){check$1(!data,"can not specify copy and data field for the same texture");var viewW=contextState.viewportWidth;var viewH=contextState.viewportHeight;image.width=image.width||viewW-image.xOffset;image.height=image.height||viewH-image.yOffset;image.needsCopy=true;check$1(image.xOffset>=0&&image.xOffset=0&&image.yOffset0&&image.width<=viewW&&image.height>0&&image.height<=viewH,"copy texture read out of bounds")}else if(!data){image.width=image.width||1;image.height=image.height||1;image.channels=image.channels||4}else if(isTypedArray(data)){image.channels=image.channels||4;image.data=data;if(!("type"in options)&&image.type===GL_UNSIGNED_BYTE$5){image.type=typedArrayCode$1(data)}}else if(isNumericArray(data)){image.channels=image.channels||4;convertData(image,data);image.alignment=1;image.needsFree=true}else if(isNDArrayLike(data)){var array=data.data;if(!Array.isArray(array)&&image.type===GL_UNSIGNED_BYTE$5){image.type=typedArrayCode$1(array)}var shape=data.shape;var stride=data.stride;var shapeX,shapeY,shapeC,strideX,strideY,strideC;if(shape.length===3){shapeC=shape[2];strideC=stride[2]}else{check$1(shape.length===2,"invalid ndarray pixel data, must be 2 or 3D");shapeC=1;strideC=1}shapeX=shape[0];shapeY=shape[1];strideX=stride[0];strideY=stride[1];image.alignment=1;image.width=shapeX;image.height=shapeY;image.channels=shapeC;image.format=image.internalformat=CHANNELS_FORMAT[shapeC];image.needsFree=true;transposeData(image,array,strideX,strideY,strideC,data.offset)}else if(isCanvasElement(data)||isOffscreenCanvas(data)||isContext2D(data)){if(isCanvasElement(data)||isOffscreenCanvas(data)){image.element=data}else{image.element=data.canvas}image.width=image.element.width;image.height=image.element.height;image.channels=4}else if(isBitmap(data)){image.element=data;image.width=data.width;image.height=data.height;image.channels=4}else if(isImageElement(data)){image.element=data;image.width=data.naturalWidth;image.height=data.naturalHeight;image.channels=4}else if(isVideoElement(data)){image.element=data;image.width=data.videoWidth;image.height=data.videoHeight;image.channels=4}else if(isRectArray(data)){var w=image.width||data[0].length;var h=image.height||data.length;var c=image.channels;if(isArrayLike(data[0][0])){c=c||data[0][0].length}else{c=c||1}var arrayShape=flattenUtils.shape(data);var n=1;for(var dd=0;dd=0,"oes_texture_float extension not enabled")}else if(image.type===GL_HALF_FLOAT_OES$1){check$1(limits.extensions.indexOf("oes_texture_half_float")>=0,"oes_texture_half_float extension not enabled")}}function setImage(info,target,miplevel){var element=info.element;var data=info.data;var internalformat=info.internalformat;var format=info.format;var type=info.type;var width=info.width;var height=info.height;setFlags(info);if(element){gl.texImage2D(target,miplevel,format,format,type,element)}else if(info.compressed){gl.compressedTexImage2D(target,miplevel,internalformat,width,height,0,data)}else if(info.needsCopy){reglPoll();gl.copyTexImage2D(target,miplevel,format,info.xOffset,info.yOffset,width,height,0)}else{gl.texImage2D(target,miplevel,format,width,height,0,format,type,data||null)}}function setSubImage(info,target,x,y,miplevel){var element=info.element;var data=info.data;var internalformat=info.internalformat;var format=info.format;var type=info.type;var width=info.width;var height=info.height;setFlags(info);if(element){gl.texSubImage2D(target,miplevel,x,y,format,type,element)}else if(info.compressed){gl.compressedTexSubImage2D(target,miplevel,x,y,internalformat,width,height,data)}else if(info.needsCopy){reglPoll();gl.copyTexSubImage2D(target,miplevel,x,y,info.xOffset,info.yOffset,width,height)}else{gl.texSubImage2D(target,miplevel,x,y,width,height,format,type,data)}}var imagePool=[];function allocImage(){return imagePool.pop()||new TexImage}function freeImage(image){if(image.needsFree){pool.freeType(image.data)}TexImage.call(image);imagePool.push(image)}function MipMap(){TexFlags.call(this);this.genMipmaps=false;this.mipmapHint=GL_DONT_CARE;this.mipmask=0;this.images=Array(16)}function parseMipMapFromShape(mipmap,width,height){var img=mipmap.images[0]=allocImage();mipmap.mipmask=1;img.width=mipmap.width=width;img.height=mipmap.height=height;img.channels=mipmap.channels=4}function parseMipMapFromObject(mipmap,options){var imgData=null;if(isPixelData(options)){imgData=mipmap.images[0]=allocImage();copyFlags(imgData,mipmap);parseImage(imgData,options);mipmap.mipmask=1}else{parseFlags(mipmap,options);if(Array.isArray(options.mipmap)){var mipData=options.mipmap;for(var i=0;i>=i;imgData.height>>=i;parseImage(imgData,mipData[i]);mipmap.mipmask|=1<=0&&!("faces"in options)){info.genMipmaps=true}}if("mag"in options){var magFilter=options.mag;check$1.parameter(magFilter,magFilters);info.magFilter=magFilters[magFilter]}var wrapS=info.wrapS;var wrapT=info.wrapT;if("wrap"in options){var wrap=options.wrap;if(typeof wrap==="string"){check$1.parameter(wrap,wrapModes);wrapS=wrapT=wrapModes[wrap]}else if(Array.isArray(wrap)){check$1.parameter(wrap[0],wrapModes);check$1.parameter(wrap[1],wrapModes);wrapS=wrapModes[wrap[0]];wrapT=wrapModes[wrap[1]]}}else{if("wrapS"in options){var optWrapS=options.wrapS;check$1.parameter(optWrapS,wrapModes);wrapS=wrapModes[optWrapS]}if("wrapT"in options){var optWrapT=options.wrapT;check$1.parameter(optWrapT,wrapModes);wrapT=wrapModes[optWrapT]}}info.wrapS=wrapS;info.wrapT=wrapT;if("anisotropic"in options){var anisotropic=options.anisotropic;check$1(typeof anisotropic==="number"&&anisotropic>=1&&anisotropic<=limits.maxAnisotropic,"aniso samples must be between 1 and ");info.anisotropic=options.anisotropic}if("mipmap"in options){var hasMipMap=false;switch(typeof options.mipmap){case"string":check$1.parameter(options.mipmap,mipmapHint,"invalid mipmap hint");info.mipmapHint=mipmapHint[options.mipmap];info.genMipmaps=true;hasMipMap=true;break;case"boolean":hasMipMap=info.genMipmaps=options.mipmap;break;case"object":check$1(Array.isArray(options.mipmap),"invalid mipmap type");info.genMipmaps=false;hasMipMap=true;break;default:check$1.raise("invalid mipmap type")}if(hasMipMap&&!("min"in options)){info.minFilter=GL_NEAREST_MIPMAP_NEAREST$1}}}function setTexInfo(info,target){gl.texParameteri(target,GL_TEXTURE_MIN_FILTER,info.minFilter);gl.texParameteri(target,GL_TEXTURE_MAG_FILTER,info.magFilter);gl.texParameteri(target,GL_TEXTURE_WRAP_S,info.wrapS);gl.texParameteri(target,GL_TEXTURE_WRAP_T,info.wrapT);if(extensions.ext_texture_filter_anisotropic){gl.texParameteri(target,GL_TEXTURE_MAX_ANISOTROPY_EXT,info.anisotropic)}if(info.genMipmaps){gl.hint(GL_GENERATE_MIPMAP_HINT,info.mipmapHint);gl.generateMipmap(target)}}var textureCount=0;var textureSet={};var numTexUnits=limits.maxTextureUnits;var textureUnits=Array(numTexUnits).map((function(){return null}));function REGLTexture(target){TexFlags.call(this);this.mipmask=0;this.internalformat=GL_RGBA$1;this.id=textureCount++;this.refCount=1;this.target=target;this.texture=gl.createTexture();this.unit=-1;this.bindCount=0;this.texInfo=new TexInfo;if(config.profile){this.stats={size:0}}}function tempBind(texture){gl.activeTexture(GL_TEXTURE0$1);gl.bindTexture(texture.target,texture.texture)}function tempRestore(){var prev=textureUnits[0];if(prev){gl.bindTexture(prev.target,prev.texture)}else{gl.bindTexture(GL_TEXTURE_2D$1,null)}}function destroy(texture){var handle=texture.texture;check$1(handle,"must not double destroy texture");var unit=texture.unit;var target=texture.target;if(unit>=0){gl.activeTexture(GL_TEXTURE0$1+unit);gl.bindTexture(target,null);textureUnits[unit]=null}gl.deleteTexture(handle);texture.texture=null;texture.params=null;texture.pixels=null;texture.refCount=0;delete textureSet[texture.id];stats.textureCount--}extend(REGLTexture.prototype,{bind:function(){var texture=this;texture.bindCount+=1;var unit=texture.unit;if(unit<0){for(var i=0;i0){continue}other.unit=-1}textureUnits[i]=texture;unit=i;break}if(unit>=numTexUnits){check$1.raise("insufficient number of texture units")}if(config.profile&&stats.maxTextureUnits>level)-x;imageData.height=imageData.height||(texture.height>>level)-y;check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage");check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds");check$1(texture.mipmask&1<>i;++i){var _w=w>>i;var _h=h>>i;if(!_w||!_h)break;gl.texImage2D(GL_TEXTURE_2D$1,i,texture.format,_w,_h,0,texture.format,texture.type,null)}tempRestore();if(config.profile){texture.stats.size=getTextureSize(texture.internalformat,texture.type,w,h,false,false)}return reglTexture2D}reglTexture2D(a,b);reglTexture2D.subimage=subimage;reglTexture2D.resize=resize;reglTexture2D._reglType="texture2d";reglTexture2D._texture=texture;if(config.profile){reglTexture2D.stats=texture.stats}reglTexture2D.destroy=function(){texture.decRef()};return reglTexture2D}function createTextureCube(a0,a1,a2,a3,a4,a5){var texture=new REGLTexture(GL_TEXTURE_CUBE_MAP$1);textureSet[texture.id]=texture;stats.cubeCount++;var faces=new Array(6);function reglTextureCube(a0,a1,a2,a3,a4,a5){var i;var texInfo=texture.texInfo;TexInfo.call(texInfo);for(i=0;i<6;++i){faces[i]=allocMipMap()}if(typeof a0==="number"||!a0){var s=a0|0||1;for(i=0;i<6;++i){parseMipMapFromShape(faces[i],s,s)}}else if(typeof a0==="object"){if(a1){parseMipMapFromObject(faces[0],a0);parseMipMapFromObject(faces[1],a1);parseMipMapFromObject(faces[2],a2);parseMipMapFromObject(faces[3],a3);parseMipMapFromObject(faces[4],a4);parseMipMapFromObject(faces[5],a5)}else{parseTexInfo(texInfo,a0);parseFlags(texture,a0);if("faces"in a0){var faceInput=a0.faces;check$1(Array.isArray(faceInput)&&faceInput.length===6,"cube faces must be a length 6 array");for(i=0;i<6;++i){check$1(typeof faceInput[i]==="object"&&!!faceInput[i],"invalid input for cube map face");copyFlags(faces[i],texture);parseMipMapFromObject(faces[i],faceInput[i])}}else{for(i=0;i<6;++i){parseMipMapFromObject(faces[i],a0)}}}}else{check$1.raise("invalid arguments to cube map")}copyFlags(texture,faces[0]);if(!limits.npotTextureCube){check$1(isPow2$1(texture.width)&&isPow2$1(texture.height),"your browser does not support non power or two texture dimensions")}if(texInfo.genMipmaps){texture.mipmask=(faces[0].width<<1)-1}else{texture.mipmask=faces[0].mipmask}check$1.textureCube(texture,texInfo,faces,limits);texture.internalformat=faces[0].internalformat;reglTextureCube.width=faces[0].width;reglTextureCube.height=faces[0].height;tempBind(texture);for(i=0;i<6;++i){setMipMap(faces[i],GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i)}setTexInfo(texInfo,GL_TEXTURE_CUBE_MAP$1);tempRestore();if(config.profile){texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,texInfo.genMipmaps,true)}reglTextureCube.format=textureFormatsInvert[texture.internalformat];reglTextureCube.type=textureTypesInvert[texture.type];reglTextureCube.mag=magFiltersInvert[texInfo.magFilter];reglTextureCube.min=minFiltersInvert[texInfo.minFilter];reglTextureCube.wrapS=wrapModesInvert[texInfo.wrapS];reglTextureCube.wrapT=wrapModesInvert[texInfo.wrapT];for(i=0;i<6;++i){freeMipMap(faces[i])}return reglTextureCube}function subimage(face,image,x_,y_,level_){check$1(!!image,"must specify image data");check$1(typeof face==="number"&&face===(face|0)&&face>=0&&face<6,"invalid face");var x=x_|0;var y=y_|0;var level=level_|0;var imageData=allocImage();copyFlags(imageData,texture);imageData.width=0;imageData.height=0;parseImage(imageData,image);imageData.width=imageData.width||(texture.width>>level)-x;imageData.height=imageData.height||(texture.height>>level)-y;check$1(texture.type===imageData.type&&texture.format===imageData.format&&texture.internalformat===imageData.internalformat,"incompatible format for texture.subimage");check$1(x>=0&&y>=0&&x+imageData.width<=texture.width&&y+imageData.height<=texture.height,"texture.subimage write out of bounds");check$1(texture.mipmask&1<>j;++j){gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+i,j,texture.format,radius>>j,radius>>j,0,texture.format,texture.type,null)}}tempRestore();if(config.profile){texture.stats.size=getTextureSize(texture.internalformat,texture.type,reglTextureCube.width,reglTextureCube.height,false,true)}return reglTextureCube}reglTextureCube(a0,a1,a2,a3,a4,a5);reglTextureCube.subimage=subimage;reglTextureCube.resize=resize;reglTextureCube._reglType="textureCube";reglTextureCube._texture=texture;if(config.profile){reglTextureCube.stats=texture.stats}reglTextureCube.destroy=function(){texture.decRef()};return reglTextureCube}function destroyTextures(){for(var i=0;i>i,texture.height>>i,0,texture.internalformat,texture.type,null)}else{for(var j=0;j<6;++j){gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X$1+j,i,texture.internalformat,texture.width>>i,texture.height>>i,0,texture.internalformat,texture.type,null)}}}setTexInfo(texture.texInfo,texture.target)}))}function refreshTextures(){for(var i=0;i=2,"invalid renderbuffer shape");w=shape[0]|0;h=shape[1]|0}else{if("radius"in options){w=h=options.radius|0}if("width"in options){w=options.width|0}if("height"in options){h=options.height|0}}if("format"in options){check$1.parameter(options.format,formatTypes,"invalid renderbuffer format");format=formatTypes[options.format]}}else if(typeof a==="number"){w=a|0;if(typeof b==="number"){h=b|0}else{h=w}}else if(!a){w=h=1}else{check$1.raise("invalid arguments to renderbuffer constructor")}check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size");if(w===renderbuffer.width&&h===renderbuffer.height&&format===renderbuffer.format){return}reglRenderbuffer.width=renderbuffer.width=w;reglRenderbuffer.height=renderbuffer.height=h;renderbuffer.format=format;gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer);gl.renderbufferStorage(GL_RENDERBUFFER,format,w,h);check$1(gl.getError()===0,"invalid render buffer format");if(config.profile){renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height)}reglRenderbuffer.format=formatTypesInvert[renderbuffer.format];return reglRenderbuffer}function resize(w_,h_){var w=w_|0;var h=h_|0||w;if(w===renderbuffer.width&&h===renderbuffer.height){return reglRenderbuffer}check$1(w>0&&h>0&&w<=limits.maxRenderbufferSize&&h<=limits.maxRenderbufferSize,"invalid renderbuffer size");reglRenderbuffer.width=renderbuffer.width=w;reglRenderbuffer.height=renderbuffer.height=h;gl.bindRenderbuffer(GL_RENDERBUFFER,renderbuffer.renderbuffer);gl.renderbufferStorage(GL_RENDERBUFFER,renderbuffer.format,w,h);check$1(gl.getError()===0,"invalid render buffer format");if(config.profile){renderbuffer.stats.size=getRenderbufferSize(renderbuffer.format,renderbuffer.width,renderbuffer.height)}return reglRenderbuffer}reglRenderbuffer(a,b);reglRenderbuffer.resize=resize;reglRenderbuffer._reglType="renderbuffer";reglRenderbuffer._renderbuffer=renderbuffer;if(config.profile){reglRenderbuffer.stats=renderbuffer.stats}reglRenderbuffer.destroy=function(){renderbuffer.decRef()};return reglRenderbuffer}if(config.profile){stats.getTotalRenderbufferSize=function(){var total=0;Object.keys(renderbufferSet).forEach((function(key){total+=renderbufferSet[key].stats.size}));return total}}function restoreRenderbuffers(){values(renderbufferSet).forEach((function(rb){rb.renderbuffer=gl.createRenderbuffer();gl.bindRenderbuffer(GL_RENDERBUFFER,rb.renderbuffer);gl.renderbufferStorage(GL_RENDERBUFFER,rb.format,rb.width,rb.height)}));gl.bindRenderbuffer(GL_RENDERBUFFER,null)}return{create:createRenderbuffer,clear:function(){values(renderbufferSet).forEach(destroy)},restore:restoreRenderbuffers}};var GL_FRAMEBUFFER$1=36160;var GL_RENDERBUFFER$1=36161;var GL_TEXTURE_2D$2=3553;var GL_TEXTURE_CUBE_MAP_POSITIVE_X$2=34069;var GL_COLOR_ATTACHMENT0$1=36064;var GL_DEPTH_ATTACHMENT=36096;var GL_STENCIL_ATTACHMENT=36128;var GL_DEPTH_STENCIL_ATTACHMENT=33306;var GL_FRAMEBUFFER_COMPLETE$1=36053;var GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT=36054;var GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT=36055;var GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS=36057;var GL_FRAMEBUFFER_UNSUPPORTED=36061;var GL_HALF_FLOAT_OES$2=36193;var GL_UNSIGNED_BYTE$6=5121;var GL_FLOAT$5=5126;var GL_RGB$1=6407;var GL_RGBA$2=6408;var GL_DEPTH_COMPONENT$1=6402;var colorTextureFormatEnums=[GL_RGB$1,GL_RGBA$2];var textureFormatChannels=[];textureFormatChannels[GL_RGBA$2]=4;textureFormatChannels[GL_RGB$1]=3;var textureTypeSizes=[];textureTypeSizes[GL_UNSIGNED_BYTE$6]=1;textureTypeSizes[GL_FLOAT$5]=4;textureTypeSizes[GL_HALF_FLOAT_OES$2]=2;var GL_RGBA4$2=32854;var GL_RGB5_A1$2=32855;var GL_RGB565$2=36194;var GL_DEPTH_COMPONENT16$1=33189;var GL_STENCIL_INDEX8$1=36168;var GL_DEPTH_STENCIL$2=34041;var GL_SRGB8_ALPHA8_EXT$1=35907;var GL_RGBA32F_EXT$1=34836;var GL_RGBA16F_EXT$1=34842;var GL_RGB16F_EXT$1=34843;var colorRenderbufferFormatEnums=[GL_RGBA4$2,GL_RGB5_A1$2,GL_RGB565$2,GL_SRGB8_ALPHA8_EXT$1,GL_RGBA16F_EXT$1,GL_RGB16F_EXT$1,GL_RGBA32F_EXT$1];var statusCode={};statusCode[GL_FRAMEBUFFER_COMPLETE$1]="complete";statusCode[GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT]="incomplete attachment";statusCode[GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS]="incomplete dimensions";statusCode[GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT]="incomplete, missing attachment";statusCode[GL_FRAMEBUFFER_UNSUPPORTED]="unsupported";function wrapFBOState(gl,extensions,limits,textureState,renderbufferState,stats){var framebufferState={cur:null,next:null,dirty:false,setFBO:null};var colorTextureFormats=["rgba"];var colorRenderbufferFormats=["rgba4","rgb565","rgb5 a1"];if(extensions.ext_srgb){colorRenderbufferFormats.push("srgba")}if(extensions.ext_color_buffer_half_float){colorRenderbufferFormats.push("rgba16f","rgb16f")}if(extensions.webgl_color_buffer_float){colorRenderbufferFormats.push("rgba32f")}var colorTypes=["uint8"];if(extensions.oes_texture_half_float){colorTypes.push("half float","float16")}if(extensions.oes_texture_float){colorTypes.push("float","float32")}function FramebufferAttachment(target,texture,renderbuffer){this.target=target;this.texture=texture;this.renderbuffer=renderbuffer;var w=0;var h=0;if(texture){w=texture.width;h=texture.height}else if(renderbuffer){w=renderbuffer.width;h=renderbuffer.height}this.width=w;this.height=h}function decRef(attachment){if(attachment){if(attachment.texture){attachment.texture._texture.decRef()}if(attachment.renderbuffer){attachment.renderbuffer._renderbuffer.decRef()}}}function incRefAndCheckShape(attachment,width,height){if(!attachment){return}if(attachment.texture){var texture=attachment.texture._texture;var tw=Math.max(1,texture.width);var th=Math.max(1,texture.height);check$1(tw===width&&th===height,"inconsistent width/height for supplied texture");texture.refCount+=1}else{var renderbuffer=attachment.renderbuffer._renderbuffer;check$1(renderbuffer.width===width&&renderbuffer.height===height,"inconsistent width/height for renderbuffer");renderbuffer.refCount+=1}}function attach(location,attachment){if(attachment){if(attachment.texture){gl.framebufferTexture2D(GL_FRAMEBUFFER$1,location,attachment.target,attachment.texture._texture.texture,0)}else{gl.framebufferRenderbuffer(GL_FRAMEBUFFER$1,location,GL_RENDERBUFFER$1,attachment.renderbuffer._renderbuffer.renderbuffer)}}}function parseAttachment(attachment){var target=GL_TEXTURE_2D$2;var texture=null;var renderbuffer=null;var data=attachment;if(typeof attachment==="object"){data=attachment.data;if("target"in attachment){target=attachment.target|0}}check$1.type(data,"function","invalid attachment data");var type=data._reglType;if(type==="texture2d"){texture=data;check$1(target===GL_TEXTURE_2D$2)}else if(type==="textureCube"){texture=data;check$1(target>=GL_TEXTURE_CUBE_MAP_POSITIVE_X$2&&target=2,"invalid shape for framebuffer");width=shape[0];height=shape[1]}else{if("radius"in options){width=height=options.radius}if("width"in options){width=options.width}if("height"in options){height=options.height}}if("color"in options||"colors"in options){colorBuffer=options.color||options.colors;if(Array.isArray(colorBuffer)){check$1(colorBuffer.length===1||extensions.webgl_draw_buffers,"multiple render targets not supported")}}if(!colorBuffer){if("colorCount"in options){colorCount=options.colorCount|0;check$1(colorCount>0,"invalid color buffer count")}if("colorTexture"in options){colorTexture=!!options.colorTexture;colorFormat="rgba4"}if("colorType"in options){colorType=options.colorType;if(!colorTexture){if(colorType==="half float"||colorType==="float16"){check$1(extensions.ext_color_buffer_half_float,"you must enable EXT_color_buffer_half_float to use 16-bit render buffers");colorFormat="rgba16f"}else if(colorType==="float"||colorType==="float32"){check$1(extensions.webgl_color_buffer_float,"you must enable WEBGL_color_buffer_float in order to use 32-bit floating point renderbuffers");colorFormat="rgba32f"}}else{check$1(extensions.oes_texture_float||!(colorType==="float"||colorType==="float32"),"you must enable OES_texture_float in order to use floating point framebuffer objects");check$1(extensions.oes_texture_half_float||!(colorType==="half float"||colorType==="float16"),"you must enable OES_texture_half_float in order to use 16-bit floating point framebuffer objects")}check$1.oneOf(colorType,colorTypes,"invalid color type")}if("colorFormat"in options){colorFormat=options.colorFormat;if(colorTextureFormats.indexOf(colorFormat)>=0){colorTexture=true}else if(colorRenderbufferFormats.indexOf(colorFormat)>=0){colorTexture=false}else{if(colorTexture){check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture")}else{check$1.oneOf(options.colorFormat,colorRenderbufferFormats,"invalid color format for renderbuffer")}}}}if("depthTexture"in options||"depthStencilTexture"in options){depthStencilTexture=!!(options.depthTexture||options.depthStencilTexture);check$1(!depthStencilTexture||extensions.webgl_depth_texture,"webgl_depth_texture extension not supported")}if("depth"in options){if(typeof options.depth==="boolean"){needsDepth=options.depth}else{depthBuffer=options.depth;needsStencil=false}}if("stencil"in options){if(typeof options.stencil==="boolean"){needsStencil=options.stencil}else{stencilBuffer=options.stencil;needsDepth=false}}if("depthStencil"in options){if(typeof options.depthStencil==="boolean"){needsDepth=needsStencil=options.depthStencil}else{depthStencilBuffer=options.depthStencil;needsDepth=false;needsStencil=false}}}var colorAttachments=null;var depthAttachment=null;var stencilAttachment=null;var depthStencilAttachment=null;if(Array.isArray(colorBuffer)){colorAttachments=colorBuffer.map(parseAttachment)}else if(colorBuffer){colorAttachments=[parseAttachment(colorBuffer)]}else{colorAttachments=new Array(colorCount);for(i=0;i=0||colorAttachments[i].renderbuffer&&colorRenderbufferFormatEnums.indexOf(colorAttachments[i].renderbuffer._renderbuffer.format)>=0,"framebuffer color attachment "+i+" is invalid");if(colorAttachments[i]&&colorAttachments[i].texture){var colorAttachmentSize=textureFormatChannels[colorAttachments[i].texture._texture.format]*textureTypeSizes[colorAttachments[i].texture._texture.type];if(commonColorAttachmentSize===null){commonColorAttachmentSize=colorAttachmentSize}else{check$1(commonColorAttachmentSize===colorAttachmentSize,"all color attachments much have the same number of bits per pixel.")}}}incRefAndCheckShape(depthAttachment,width,height);check$1(!depthAttachment||depthAttachment.texture&&depthAttachment.texture._texture.format===GL_DEPTH_COMPONENT$1||depthAttachment.renderbuffer&&depthAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_COMPONENT16$1,"invalid depth attachment for framebuffer object");incRefAndCheckShape(stencilAttachment,width,height);check$1(!stencilAttachment||stencilAttachment.renderbuffer&&stencilAttachment.renderbuffer._renderbuffer.format===GL_STENCIL_INDEX8$1,"invalid stencil attachment for framebuffer object");incRefAndCheckShape(depthStencilAttachment,width,height);check$1(!depthStencilAttachment||depthStencilAttachment.texture&&depthStencilAttachment.texture._texture.format===GL_DEPTH_STENCIL$2||depthStencilAttachment.renderbuffer&&depthStencilAttachment.renderbuffer._renderbuffer.format===GL_DEPTH_STENCIL$2,"invalid depth-stencil attachment for framebuffer object");decFBORefs(framebuffer);framebuffer.width=width;framebuffer.height=height;framebuffer.colorAttachments=colorAttachments;framebuffer.depthAttachment=depthAttachment;framebuffer.stencilAttachment=stencilAttachment;framebuffer.depthStencilAttachment=depthStencilAttachment;reglFramebuffer.color=colorAttachments.map(unwrapAttachment);reglFramebuffer.depth=unwrapAttachment(depthAttachment);reglFramebuffer.stencil=unwrapAttachment(stencilAttachment);reglFramebuffer.depthStencil=unwrapAttachment(depthStencilAttachment);reglFramebuffer.width=framebuffer.width;reglFramebuffer.height=framebuffer.height;updateFramebuffer(framebuffer);return reglFramebuffer}function resize(w_,h_){check$1(framebufferState.next!==framebuffer,"can not resize a framebuffer which is currently in use");var w=Math.max(w_|0,1);var h=Math.max(h_|0||w,1);if(w===framebuffer.width&&h===framebuffer.height){return reglFramebuffer}var colorAttachments=framebuffer.colorAttachments;for(var i=0;i=2,"invalid shape for framebuffer");check$1(shape[0]===shape[1],"cube framebuffer must be square");radius=shape[0]}else{if("radius"in options){radius=options.radius|0}if("width"in options){radius=options.width|0;if("height"in options){check$1(options.height===radius,"must be square")}}else if("height"in options){radius=options.height|0}}if("color"in options||"colors"in options){colorBuffer=options.color||options.colors;if(Array.isArray(colorBuffer)){check$1(colorBuffer.length===1||extensions.webgl_draw_buffers,"multiple render targets not supported")}}if(!colorBuffer){if("colorCount"in options){colorCount=options.colorCount|0;check$1(colorCount>0,"invalid color buffer count")}if("colorType"in options){check$1.oneOf(options.colorType,colorTypes,"invalid color type");colorType=options.colorType}if("colorFormat"in options){colorFormat=options.colorFormat;check$1.oneOf(options.colorFormat,colorTextureFormats,"invalid color format for texture")}}if("depth"in options){params.depth=options.depth}if("stencil"in options){params.stencil=options.stencil}if("depthStencil"in options){params.depthStencil=options.depthStencil}}var colorCubes;if(colorBuffer){if(Array.isArray(colorBuffer)){colorCubes=[];for(i=0;i0){params.depth=faces[0].depth;params.stencil=faces[0].stencil;params.depthStencil=faces[0].depthStencil}if(faces[i]){faces[i](params)}else{faces[i]=createFBO(params)}}return extend(reglFramebufferCube,{width:radius,height:radius,color:colorCubes})}function resize(radius_){var i;var radius=radius_|0;check$1(radius>0&&radius<=limits.maxCubeMapSize,"invalid radius for cube fbo");if(radius===reglFramebufferCube.width){return reglFramebufferCube}var colors=reglFramebufferCube.color;for(i=0;i0,"must specify at least one attribute");var bufUpdated={};var nattributes=vao.attributes;nattributes.length=attributes.length;for(var i=0;i=data.byteLength){buf.subdata(data)}else{buf.destroy();vao.buffers[i]=null}}if(!vao.buffers[i]){buf=vao.buffers[i]=bufferState.create(spec,GL_ARRAY_BUFFER$1,false,true)}rec.buffer=bufferState.getBuffer(buf);rec.size=rec.buffer.dimension|0;rec.normalized=false;rec.type=rec.buffer.dtype;rec.offset=0;rec.stride=0;rec.divisor=0;rec.state=1;bufUpdated[i]=1}else if(bufferState.getBuffer(spec)){rec.buffer=bufferState.getBuffer(spec);rec.size=rec.buffer.dimension|0;rec.normalized=false;rec.type=rec.buffer.dtype;rec.offset=0;rec.stride=0;rec.divisor=0;rec.state=1}else if(bufferState.getBuffer(spec.buffer)){rec.buffer=bufferState.getBuffer(spec.buffer);rec.size=(+spec.size||rec.buffer.dimension)|0;rec.normalized=!!spec.normalized||false;if("type"in spec){check$1.parameter(spec.type,glTypes,"invalid buffer type");rec.type=glTypes[spec.type]}else{rec.type=rec.buffer.dtype}rec.offset=(spec.offset||0)|0;rec.stride=(spec.stride||0)|0;rec.divisor=(spec.divisor||0)|0;rec.state=1;check$1(rec.size>=1&&rec.size<=4,"size must be between 1 and 4");check$1(rec.offset>=0,"invalid offset");check$1(rec.stride>=0&&rec.stride<=255,"stride must be between 0 and 255");check$1(rec.divisor>=0,"divisor must be positive");check$1(!rec.divisor||!!extensions.angle_instanced_arrays,"ANGLE_instanced_arrays must be enabled to use divisor")}else if("x"in spec){check$1(i>0,"first attribute must not be a constant");rec.x=+spec.x||0;rec.y=+spec.y||0;rec.z=+spec.z||0;rec.w=+spec.w||0;rec.state=2}else{check$1(false,"invalid attribute spec for location "+i)}}for(var j=0;j1){for(var j=0;jm){m=desc.stats.uniformsCount}}));return m};stats.getMaxAttributesCount=function(){var m=0;programList.forEach((function(desc){if(desc.stats.attributesCount>m){m=desc.stats.attributesCount}}));return m}}function restoreShaders(){fragShaders={};vertShaders={};for(var i=0;i=0,"missing vertex shader",command);check$1.command(fragId>=0,"missing fragment shader",command);var cache=programCache[fragId];if(!cache){cache=programCache[fragId]={}}var prevProgram=cache[vertId];if(prevProgram){prevProgram.refCount++;if(!attribLocations){return prevProgram}}var program=new REGLProgram(fragId,vertId);stats.shaderCount++;linkProgram(program,command,attribLocations);if(!prevProgram){cache[vertId]=program}programList.push(program);return extend(program,{destroy:function(){program.refCount--;if(program.refCount<=0){gl.deleteProgram(program.program);var idx=programList.indexOf(program);programList.splice(idx,1);stats.shaderCount--}if(cache[program.vertId].refCount<=0){gl.deleteShader(vertShaders[program.vertId]);delete vertShaders[program.vertId];delete programCache[program.fragId][program.vertId]}if(!Object.keys(programCache[program.fragId]).length){gl.deleteShader(fragShaders[program.fragId]);delete fragShaders[program.fragId];delete programCache[program.fragId]}}})},restore:restoreShaders,shader:getShader,frag:-1,vert:-1}}var GL_RGBA$3=6408;var GL_UNSIGNED_BYTE$7=5121;var GL_PACK_ALIGNMENT=3333;var GL_FLOAT$7=5126;function wrapReadPixels(gl,framebufferState,reglPoll,context,glAttributes,extensions,limits){function readPixelsImpl(input){var type;if(framebufferState.next===null){check$1(glAttributes.preserveDrawingBuffer,'you must create a webgl context with "preserveDrawingBuffer":true in order to read pixels from the drawing buffer');type=GL_UNSIGNED_BYTE$7}else{check$1(framebufferState.next.colorAttachments[0].texture!==null,"You cannot read from a renderbuffer");type=framebufferState.next.colorAttachments[0].texture._texture.type;if(extensions.oes_texture_float){check$1(type===GL_UNSIGNED_BYTE$7||type===GL_FLOAT$7,"Reading from a framebuffer is only allowed for the types 'uint8' and 'float'");if(type===GL_FLOAT$7){check$1(limits.readFloat,"Reading 'float' values is not permitted in your browser. For a fallback, please see: https://www.npmjs.com/package/glsl-read-float")}}else{check$1(type===GL_UNSIGNED_BYTE$7,"Reading from a framebuffer is only allowed for the type 'uint8'")}}var x=0;var y=0;var width=context.framebufferWidth;var height=context.framebufferHeight;var data=null;if(isTypedArray(input)){data=input}else if(input){check$1.type(input,"object","invalid arguments to regl.read()");x=input.x|0;y=input.y|0;check$1(x>=0&&x=0&&y0&&width+x<=context.framebufferWidth,"invalid width for read pixels");check$1(height>0&&height+y<=context.framebufferHeight,"invalid height for read pixels");reglPoll();var size=width*height*4;if(!data){if(type===GL_UNSIGNED_BYTE$7){data=new Uint8Array(size)}else if(type===GL_FLOAT$7){data=data||new Float32Array(size)}}check$1.isTypedArray(data,"data buffer for regl.read() must be a typedarray");check$1(data.byteLength>=size,"data buffer for regl.read() too small");gl.pixelStorei(GL_PACK_ALIGNMENT,4);gl.readPixels(x,y,width,height,GL_RGBA$3,type,data);return data}function readPixelsFBO(options){var result;framebufferState.setFBO({framebuffer:options.framebuffer},(function(){result=readPixelsImpl(options)}));return result}function readPixels(options){if(!options||!("framebuffer"in options)){return readPixelsImpl(options)}else{return readPixelsFBO(options)}}return readPixels}function slice(x){return Array.prototype.slice.call(x)}function join(x){return slice(x).join("")}function createEnvironment(){var varCounter=0;var linkedNames=[];var linkedValues=[];function link(value){for(var i=0;i0){code.push(name,"=");code.push.apply(code,slice(arguments));code.push(";")}return name}return extend(push,{def:def,toString:function(){return join([vars.length>0?"var "+vars.join(",")+";":"",join(code)])}})}function scope(){var entry=block();var exit=block();var entryToString=entry.toString;var exitToString=exit.toString;function save(object,prop){exit(object,prop,"=",entry.def(object,prop),";")}return extend((function(){entry.apply(entry,slice(arguments))}),{def:entry.def,entry:entry,exit:exit,save:save,set:function(object,prop,value){save(object,prop);entry(object,prop,"=",value,";")},toString:function(){return entryToString()+exitToString()}})}function conditional(){var pred=join(arguments);var thenBlock=scope();var elseBlock=scope();var thenToString=thenBlock.toString;var elseToString=elseBlock.toString;return extend(thenBlock,{then:function(){thenBlock.apply(thenBlock,slice(arguments));return this},else:function(){elseBlock.apply(elseBlock,slice(arguments));return this},toString:function(){var elseClause=elseToString();if(elseClause){elseClause="else{"+elseClause+"}"}return join(["if(",pred,"){",thenToString(),"}",elseClause])}})}var globalBlock=block();var procedures={};function proc(name,count){var args=[];function arg(){var name="a"+args.length;args.push(name);return name}count=count||0;for(var i=0;i":516,notequal:517,"!=":517,"!==":517,gequal:518,">=":518,always:519};var stencilOps={0:0,zero:0,keep:7680,replace:7681,increment:7682,decrement:7683,"increment wrap":34055,"decrement wrap":34056,invert:5386};var shaderType={frag:GL_FRAGMENT_SHADER$1,vert:GL_VERTEX_SHADER$1};var orientationType={cw:GL_CW,ccw:GL_CCW};function isBufferArgs(x){return Array.isArray(x)||isTypedArray(x)||isNDArrayLike(x)}function sortState(state){return state.sort((function(a,b){if(a===S_VIEWPORT){return-1}else if(b===S_VIEWPORT){return 1}return a=1,numArgs>=2,append)}else if(type===DYN_THUNK){var data=dyn.data;return new Declaration(data.thisDep,data.contextDep,data.propDep,append)}else if(type===DYN_CONSTANT$1){return new Declaration(false,false,false,append)}else if(type===DYN_ARRAY$1){var thisDep=false;var contextDep=false;var propDep=false;for(var i=0;i=1){contextDep=true}if(subArgs>=2){propDep=true}}else if(subDyn.type===DYN_THUNK){thisDep=thisDep||subDyn.data.thisDep;contextDep=contextDep||subDyn.data.contextDep;propDep=propDep||subDyn.data.propDep}}return new Declaration(thisDep,contextDep,propDep,append)}else{return new Declaration(type===DYN_STATE$1,type===DYN_CONTEXT$1,type===DYN_PROP$1,append)}}var SCOPE_DECL=new Declaration(false,false,false,(function(){}));function reglCore(gl,stringStore,extensions,limits,bufferState,elementState,textureState,framebufferState,uniformState,attributeState,shaderState,drawState,contextState,timer,config){var AttributeRecord=attributeState.Record;var blendEquations={add:32774,subtract:32778,"reverse subtract":32779};if(extensions.ext_blend_minmax){blendEquations.min=GL_MIN_EXT;blendEquations.max=GL_MAX_EXT}var extInstancing=extensions.angle_instanced_arrays;var extDrawBuffers=extensions.webgl_draw_buffers;var currentState={dirty:true,profile:config.profile};var nextState={};var GL_STATE_NAMES=[];var GL_FLAGS={};var GL_VARIABLES={};function propName(name){return name.replace(".","_")}function stateFlag(sname,cap,init){var name=propName(sname);GL_STATE_NAMES.push(sname);nextState[name]=currentState[name]=!!init;GL_FLAGS[name]=cap}function stateVariable(sname,func,init){var name=propName(sname);GL_STATE_NAMES.push(sname);if(Array.isArray(init)){currentState[name]=init.slice();nextState[name]=init.slice()}else{currentState[name]=nextState[name]=init}GL_VARIABLES[name]=func}stateFlag(S_DITHER,GL_DITHER);stateFlag(S_BLEND_ENABLE,GL_BLEND);stateVariable(S_BLEND_COLOR,"blendColor",[0,0,0,0]);stateVariable(S_BLEND_EQUATION,"blendEquationSeparate",[GL_FUNC_ADD,GL_FUNC_ADD]);stateVariable(S_BLEND_FUNC,"blendFuncSeparate",[GL_ONE,GL_ZERO,GL_ONE,GL_ZERO]);stateFlag(S_DEPTH_ENABLE,GL_DEPTH_TEST,true);stateVariable(S_DEPTH_FUNC,"depthFunc",GL_LESS);stateVariable(S_DEPTH_RANGE,"depthRange",[0,1]);stateVariable(S_DEPTH_MASK,"depthMask",true);stateVariable(S_COLOR_MASK,S_COLOR_MASK,[true,true,true,true]);stateFlag(S_CULL_ENABLE,GL_CULL_FACE);stateVariable(S_CULL_FACE,"cullFace",GL_BACK);stateVariable(S_FRONT_FACE,S_FRONT_FACE,GL_CCW);stateVariable(S_LINE_WIDTH,S_LINE_WIDTH,1);stateFlag(S_POLYGON_OFFSET_ENABLE,GL_POLYGON_OFFSET_FILL);stateVariable(S_POLYGON_OFFSET_OFFSET,"polygonOffset",[0,0]);stateFlag(S_SAMPLE_ALPHA,GL_SAMPLE_ALPHA_TO_COVERAGE);stateFlag(S_SAMPLE_ENABLE,GL_SAMPLE_COVERAGE);stateVariable(S_SAMPLE_COVERAGE,"sampleCoverage",[1,false]);stateFlag(S_STENCIL_ENABLE,GL_STENCIL_TEST);stateVariable(S_STENCIL_MASK,"stencilMask",-1);stateVariable(S_STENCIL_FUNC,"stencilFunc",[GL_ALWAYS,0,-1]);stateVariable(S_STENCIL_OPFRONT,"stencilOpSeparate",[GL_FRONT,GL_KEEP,GL_KEEP,GL_KEEP]);stateVariable(S_STENCIL_OPBACK,"stencilOpSeparate",[GL_BACK,GL_KEEP,GL_KEEP,GL_KEEP]);stateFlag(S_SCISSOR_ENABLE,GL_SCISSOR_TEST);stateVariable(S_SCISSOR_BOX,"scissor",[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]);stateVariable(S_VIEWPORT,S_VIEWPORT,[0,0,gl.drawingBufferWidth,gl.drawingBufferHeight]);var sharedState={gl:gl,context:contextState,strings:stringStore,next:nextState,current:currentState,draw:drawState,elements:elementState,buffer:bufferState,shader:shaderState,attributes:attributeState.state,vao:attributeState,uniforms:uniformState,framebuffer:framebufferState,extensions:extensions,timer:timer,isBufferArgs:isBufferArgs};var sharedConstants={primTypes:primTypes,compareFuncs:compareFuncs,blendFuncs:blendFuncs,blendEquations:blendEquations,stencilOps:stencilOps,glTypes:glTypes,orientationType:orientationType};check$1.optional((function(){sharedState.isArrayLike=isArrayLike}));if(extDrawBuffers){sharedConstants.backBuffer=[GL_BACK];sharedConstants.drawBuffer=loop(limits.maxDrawbuffers,(function(i){if(i===0){return[0]}return loop(i,(function(j){return GL_COLOR_ATTACHMENT0$2+j}))}))}var drawCallCounter=0;function createREGLEnvironment(){var env=createEnvironment();var link=env.link;var global=env.global;env.id=drawCallCounter++;env.batchId="0";var SHARED=link(sharedState);var shared=env.shared={props:"a0"};Object.keys(sharedState).forEach((function(prop){shared[prop]=global.def(SHARED,".",prop)}));check$1.optional((function(){env.CHECK=link(check$1);env.commandStr=check$1.guessCommand();env.command=link(env.commandStr);env.assert=function(block,pred,message){block("if(!(",pred,"))",this.CHECK,".commandRaise(",link(message),",",this.command,");")};sharedConstants.invalidBlendCombinations=invalidBlendCombinations}));var nextVars=env.next={};var currentVars=env.current={};Object.keys(GL_VARIABLES).forEach((function(variable){if(Array.isArray(currentState[variable])){nextVars[variable]=global.def(shared.next,".",variable);currentVars[variable]=global.def(shared.current,".",variable)}}));var constants=env.constants={};Object.keys(sharedConstants).forEach((function(name){constants[name]=global.def(JSON.stringify(sharedConstants[name]))}));env.invoke=function(block,x){switch(x.type){case DYN_FUNC$1:var argList=["this",shared.context,shared.props,env.batchId];return block.def(link(x.data),".call(",argList.slice(0,Math.max(x.data.length+1,4)),")");case DYN_PROP$1:return block.def(shared.props,x.data);case DYN_CONTEXT$1:return block.def(shared.context,x.data);case DYN_STATE$1:return block.def("this",x.data);case DYN_THUNK:x.data.append(env,block);return x.data.ref;case DYN_CONSTANT$1:return x.data.toString();case DYN_ARRAY$1:return x.data.map((function(y){return env.invoke(block,y)}))}};env.attribCache={};var scopeAttribs={};env.scopeAttrib=function(name){var id=stringStore.id(name);if(id in scopeAttribs){return scopeAttribs[id]}var binding=attributeState.scope[id];if(!binding){binding=attributeState.scope[id]=new AttributeRecord}var result=scopeAttribs[id]=link(binding);return result};return env}function parseProfile(options){var staticOptions=options.static;var dynamicOptions=options.dynamic;var profileEnable;if(S_PROFILE in staticOptions){var value=!!staticOptions[S_PROFILE];profileEnable=createStaticDecl((function(env,scope){return value}));profileEnable.enable=value}else if(S_PROFILE in dynamicOptions){var dyn=dynamicOptions[S_PROFILE];profileEnable=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))}return profileEnable}function parseFramebuffer(options,env){var staticOptions=options.static;var dynamicOptions=options.dynamic;if(S_FRAMEBUFFER in staticOptions){var framebuffer=staticOptions[S_FRAMEBUFFER];if(framebuffer){framebuffer=framebufferState.getFramebuffer(framebuffer);check$1.command(framebuffer,"invalid framebuffer object");return createStaticDecl((function(env,block){var FRAMEBUFFER=env.link(framebuffer);var shared=env.shared;block.set(shared.framebuffer,".next",FRAMEBUFFER);var CONTEXT=shared.context;block.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+".width");block.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+".height");return FRAMEBUFFER}))}else{return createStaticDecl((function(env,scope){var shared=env.shared;scope.set(shared.framebuffer,".next","null");var CONTEXT=shared.context;scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,CONTEXT+"."+S_DRAWINGBUFFER_WIDTH);scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT);return"null"}))}}else if(S_FRAMEBUFFER in dynamicOptions){var dyn=dynamicOptions[S_FRAMEBUFFER];return createDynamicDecl(dyn,(function(env,scope){var FRAMEBUFFER_FUNC=env.invoke(scope,dyn);var shared=env.shared;var FRAMEBUFFER_STATE=shared.framebuffer;var FRAMEBUFFER=scope.def(FRAMEBUFFER_STATE,".getFramebuffer(",FRAMEBUFFER_FUNC,")");check$1.optional((function(){env.assert(scope,"!"+FRAMEBUFFER_FUNC+"||"+FRAMEBUFFER,"invalid framebuffer object")}));scope.set(FRAMEBUFFER_STATE,".next",FRAMEBUFFER);var CONTEXT=shared.context;scope.set(CONTEXT,"."+S_FRAMEBUFFER_WIDTH,FRAMEBUFFER+"?"+FRAMEBUFFER+".width:"+CONTEXT+"."+S_DRAWINGBUFFER_WIDTH);scope.set(CONTEXT,"."+S_FRAMEBUFFER_HEIGHT,FRAMEBUFFER+"?"+FRAMEBUFFER+".height:"+CONTEXT+"."+S_DRAWINGBUFFER_HEIGHT);return FRAMEBUFFER}))}else{return null}}function parseViewportScissor(options,framebuffer,env){var staticOptions=options.static;var dynamicOptions=options.dynamic;function parseBox(param){if(param in staticOptions){var box=staticOptions[param];check$1.commandType(box,"object","invalid "+param,env.commandStr);var isStatic=true;var x=box.x|0;var y=box.y|0;var w,h;if("width"in box){w=box.width|0;check$1.command(w>=0,"invalid "+param,env.commandStr)}else{isStatic=false}if("height"in box){h=box.height|0;check$1.command(h>=0,"invalid "+param,env.commandStr)}else{isStatic=false}return new Declaration(!isStatic&&framebuffer&&framebuffer.thisDep,!isStatic&&framebuffer&&framebuffer.contextDep,!isStatic&&framebuffer&&framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context;var BOX_W=w;if(!("width"in box)){BOX_W=scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",x)}var BOX_H=h;if(!("height"in box)){BOX_H=scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",y)}return[x,y,BOX_W,BOX_H]}))}else if(param in dynamicOptions){var dynBox=dynamicOptions[param];var result=createDynamicDecl(dynBox,(function(env,scope){var BOX=env.invoke(scope,dynBox);check$1.optional((function(){env.assert(scope,BOX+"&&typeof "+BOX+'==="object"',"invalid "+param)}));var CONTEXT=env.shared.context;var BOX_X=scope.def(BOX,".x|0");var BOX_Y=scope.def(BOX,".y|0");var BOX_W=scope.def('"width" in ',BOX,"?",BOX,".width|0:","(",CONTEXT,".",S_FRAMEBUFFER_WIDTH,"-",BOX_X,")");var BOX_H=scope.def('"height" in ',BOX,"?",BOX,".height|0:","(",CONTEXT,".",S_FRAMEBUFFER_HEIGHT,"-",BOX_Y,")");check$1.optional((function(){env.assert(scope,BOX_W+">=0&&"+BOX_H+">=0","invalid "+param)}));return[BOX_X,BOX_Y,BOX_W,BOX_H]}));if(framebuffer){result.thisDep=result.thisDep||framebuffer.thisDep;result.contextDep=result.contextDep||framebuffer.contextDep;result.propDep=result.propDep||framebuffer.propDep}return result}else if(framebuffer){return new Declaration(framebuffer.thisDep,framebuffer.contextDep,framebuffer.propDep,(function(env,scope){var CONTEXT=env.shared.context;return[0,0,scope.def(CONTEXT,".",S_FRAMEBUFFER_WIDTH),scope.def(CONTEXT,".",S_FRAMEBUFFER_HEIGHT)]}))}else{return null}}var viewport=parseBox(S_VIEWPORT);if(viewport){var prevViewport=viewport;viewport=new Declaration(viewport.thisDep,viewport.contextDep,viewport.propDep,(function(env,scope){var VIEWPORT=prevViewport.append(env,scope);var CONTEXT=env.shared.context;scope.set(CONTEXT,"."+S_VIEWPORT_WIDTH,VIEWPORT[2]);scope.set(CONTEXT,"."+S_VIEWPORT_HEIGHT,VIEWPORT[3]);return VIEWPORT}))}return{viewport:viewport,scissor_box:parseBox(S_SCISSOR_BOX)}}function parseAttribLocations(options,attributes){var staticOptions=options.static;var staticProgram=typeof staticOptions[S_FRAG]==="string"&&typeof staticOptions[S_VERT]==="string";if(staticProgram){if(Object.keys(attributes.dynamic).length>0){return null}var staticAttributes=attributes.static;var sAttributes=Object.keys(staticAttributes);if(sAttributes.length>0&&typeof staticAttributes[sAttributes[0]]==="number"){var bindings=[];for(var i=0;i=0,"invalid "+param,env.commandStr);return createStaticDecl((function(env,scope){if(isOffset){env.OFFSET=value}return value}))}else if(param in dynamicOptions){var dynValue=dynamicOptions[param];return createDynamicDecl(dynValue,(function(env,scope){var result=env.invoke(scope,dynValue);if(isOffset){env.OFFSET=result;check$1.optional((function(){env.assert(scope,result+">=0","invalid "+param)}))}return result}))}else if(isOffset&&elements){return createStaticDecl((function(env,scope){env.OFFSET="0";return 0}))}return null}var OFFSET=parseParam(S_OFFSET,true);function parseVertCount(){if(S_COUNT in staticOptions){var count=staticOptions[S_COUNT]|0;check$1.command(typeof count==="number"&&count>=0,"invalid vertex count",env.commandStr);return createStaticDecl((function(){return count}))}else if(S_COUNT in dynamicOptions){var dynCount=dynamicOptions[S_COUNT];return createDynamicDecl(dynCount,(function(env,scope){var result=env.invoke(scope,dynCount);check$1.optional((function(){env.assert(scope,"typeof "+result+'==="number"&&'+result+">=0&&"+result+"===("+result+"|0)","invalid vertex count")}));return result}))}else if(elements){if(isStatic(elements)){if(elements){if(OFFSET){return new Declaration(OFFSET.thisDep,OFFSET.contextDep,OFFSET.propDep,(function(env,scope){var result=scope.def(env.ELEMENTS,".vertCount-",env.OFFSET);check$1.optional((function(){env.assert(scope,result+">=0","invalid vertex offset/element buffer too small")}));return result}))}else{return createStaticDecl((function(env,scope){return scope.def(env.ELEMENTS,".vertCount")}))}}else{var result=createStaticDecl((function(){return-1}));check$1.optional((function(){result.MISSING=true}));return result}}else{var variable=new Declaration(elements.thisDep||OFFSET.thisDep,elements.contextDep||OFFSET.contextDep,elements.propDep||OFFSET.propDep,(function(env,scope){var elements=env.ELEMENTS;if(env.OFFSET){return scope.def(elements,"?",elements,".vertCount-",env.OFFSET,":-1")}return scope.def(elements,"?",elements,".vertCount:-1")}));check$1.optional((function(){variable.DYNAMIC=true}));return variable}}return null}return{elements:elements,primitive:parsePrimitive(),count:parseVertCount(),instances:parseParam(S_INSTANCES,false),offset:OFFSET}}function parseGLState(options,env){var staticOptions=options.static;var dynamicOptions=options.dynamic;var STATE={};GL_STATE_NAMES.forEach((function(prop){var param=propName(prop);function parseParam(parseStatic,parseDynamic){if(prop in staticOptions){var value=parseStatic(staticOptions[prop]);STATE[param]=createStaticDecl((function(){return value}))}else if(prop in dynamicOptions){var dyn=dynamicOptions[prop];STATE[param]=createDynamicDecl(dyn,(function(env,scope){return parseDynamic(env,scope,env.invoke(scope,dyn))}))}}switch(prop){case S_CULL_ENABLE:case S_BLEND_ENABLE:case S_DITHER:case S_STENCIL_ENABLE:case S_DEPTH_ENABLE:case S_SCISSOR_ENABLE:case S_POLYGON_OFFSET_ENABLE:case S_SAMPLE_ALPHA:case S_SAMPLE_ENABLE:case S_DEPTH_MASK:return parseParam((function(value){check$1.commandType(value,"boolean",prop,env.commandStr);return value}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,"typeof "+value+'==="boolean"',"invalid flag "+prop,env.commandStr)}));return value}));case S_DEPTH_FUNC:return parseParam((function(value){check$1.commandParameter(value,compareFuncs,"invalid "+prop,env.commandStr);return compareFuncs[value]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;check$1.optional((function(){env.assert(scope,value+" in "+COMPARE_FUNCS,"invalid "+prop+", must be one of "+Object.keys(compareFuncs))}));return scope.def(COMPARE_FUNCS,"[",value,"]")}));case S_DEPTH_RANGE:return parseParam((function(value){check$1.command(isArrayLike(value)&&value.length===2&&typeof value[0]==="number"&&typeof value[1]==="number"&&value[0]<=value[1],"depth range is 2d array",env.commandStr);return value}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===2&&"+"typeof "+value+'[0]==="number"&&'+"typeof "+value+'[1]==="number"&&'+value+"[0]<="+value+"[1]","depth range must be a 2d array")}));var Z_NEAR=scope.def("+",value,"[0]");var Z_FAR=scope.def("+",value,"[1]");return[Z_NEAR,Z_FAR]}));case S_BLEND_FUNC:return parseParam((function(value){check$1.commandType(value,"object","blend.func",env.commandStr);var srcRGB="srcRGB"in value?value.srcRGB:value.src;var srcAlpha="srcAlpha"in value?value.srcAlpha:value.src;var dstRGB="dstRGB"in value?value.dstRGB:value.dst;var dstAlpha="dstAlpha"in value?value.dstAlpha:value.dst;check$1.commandParameter(srcRGB,blendFuncs,param+".srcRGB",env.commandStr);check$1.commandParameter(srcAlpha,blendFuncs,param+".srcAlpha",env.commandStr);check$1.commandParameter(dstRGB,blendFuncs,param+".dstRGB",env.commandStr);check$1.commandParameter(dstAlpha,blendFuncs,param+".dstAlpha",env.commandStr);check$1.command(invalidBlendCombinations.indexOf(srcRGB+", "+dstRGB)===-1,"unallowed blending combination (srcRGB, dstRGB) = ("+srcRGB+", "+dstRGB+")",env.commandStr);return[blendFuncs[srcRGB],blendFuncs[dstRGB],blendFuncs[srcAlpha],blendFuncs[dstAlpha]]}),(function(env,scope,value){var BLEND_FUNCS=env.constants.blendFuncs;check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid blend func, must be an object")}));function read(prefix,suffix){var func=scope.def('"',prefix,suffix,'" in ',value,"?",value,".",prefix,suffix,":",value,".",prefix);check$1.optional((function(){env.assert(scope,func+" in "+BLEND_FUNCS,"invalid "+prop+"."+prefix+suffix+", must be one of "+Object.keys(blendFuncs))}));return func}var srcRGB=read("src","RGB");var dstRGB=read("dst","RGB");check$1.optional((function(){var INVALID_BLEND_COMBINATIONS=env.constants.invalidBlendCombinations;env.assert(scope,INVALID_BLEND_COMBINATIONS+".indexOf("+srcRGB+'+", "+'+dstRGB+") === -1 ","unallowed blending combination for (srcRGB, dstRGB)")}));var SRC_RGB=scope.def(BLEND_FUNCS,"[",srcRGB,"]");var SRC_ALPHA=scope.def(BLEND_FUNCS,"[",read("src","Alpha"),"]");var DST_RGB=scope.def(BLEND_FUNCS,"[",dstRGB,"]");var DST_ALPHA=scope.def(BLEND_FUNCS,"[",read("dst","Alpha"),"]");return[SRC_RGB,DST_RGB,SRC_ALPHA,DST_ALPHA]}));case S_BLEND_EQUATION:return parseParam((function(value){if(typeof value==="string"){check$1.commandParameter(value,blendEquations,"invalid "+prop,env.commandStr);return[blendEquations[value],blendEquations[value]]}else if(typeof value==="object"){check$1.commandParameter(value.rgb,blendEquations,prop+".rgb",env.commandStr);check$1.commandParameter(value.alpha,blendEquations,prop+".alpha",env.commandStr);return[blendEquations[value.rgb],blendEquations[value.alpha]]}else{check$1.commandRaise("invalid blend.equation",env.commandStr)}}),(function(env,scope,value){var BLEND_EQUATIONS=env.constants.blendEquations;var RGB=scope.def();var ALPHA=scope.def();var ifte=env.cond("typeof ",value,'==="string"');check$1.optional((function(){function checkProp(block,name,value){env.assert(block,value+" in "+BLEND_EQUATIONS,"invalid "+name+", must be one of "+Object.keys(blendEquations))}checkProp(ifte.then,prop,value);env.assert(ifte.else,value+"&&typeof "+value+'==="object"',"invalid "+prop);checkProp(ifte.else,prop+".rgb",value+".rgb");checkProp(ifte.else,prop+".alpha",value+".alpha")}));ifte.then(RGB,"=",ALPHA,"=",BLEND_EQUATIONS,"[",value,"];");ifte.else(RGB,"=",BLEND_EQUATIONS,"[",value,".rgb];",ALPHA,"=",BLEND_EQUATIONS,"[",value,".alpha];");scope(ifte);return[RGB,ALPHA]}));case S_BLEND_COLOR:return parseParam((function(value){check$1.command(isArrayLike(value)&&value.length===4,"blend.color must be a 4d array",env.commandStr);return loop(4,(function(i){return+value[i]}))}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","blend.color must be a 4d array")}));return loop(4,(function(i){return scope.def("+",value,"[",i,"]")}))}));case S_STENCIL_MASK:return parseParam((function(value){check$1.commandType(value,"number",param,env.commandStr);return value|0}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"',"invalid stencil.mask")}));return scope.def(value,"|0")}));case S_STENCIL_FUNC:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var cmp=value.cmp||"keep";var ref=value.ref||0;var mask="mask"in value?value.mask:-1;check$1.commandParameter(cmp,compareFuncs,prop+".cmp",env.commandStr);check$1.commandType(ref,"number",prop+".ref",env.commandStr);check$1.commandType(mask,"number",prop+".mask",env.commandStr);return[compareFuncs[cmp],ref,mask]}),(function(env,scope,value){var COMPARE_FUNCS=env.constants.compareFuncs;check$1.optional((function(){function assert(){env.assert(scope,Array.prototype.join.call(arguments,""),"invalid stencil.func")}assert(value+"&&typeof ",value,'==="object"');assert('!("cmp" in ',value,")||(",value,".cmp in ",COMPARE_FUNCS,")")}));var cmp=scope.def('"cmp" in ',value,"?",COMPARE_FUNCS,"[",value,".cmp]",":",GL_KEEP);var ref=scope.def(value,".ref|0");var mask=scope.def('"mask" in ',value,"?",value,".mask|0:-1");return[cmp,ref,mask]}));case S_STENCIL_OPFRONT:case S_STENCIL_OPBACK:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var fail=value.fail||"keep";var zfail=value.zfail||"keep";var zpass=value.zpass||"keep";check$1.commandParameter(fail,stencilOps,prop+".fail",env.commandStr);check$1.commandParameter(zfail,stencilOps,prop+".zfail",env.commandStr);check$1.commandParameter(zpass,stencilOps,prop+".zpass",env.commandStr);return[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,stencilOps[fail],stencilOps[zfail],stencilOps[zpass]]}),(function(env,scope,value){var STENCIL_OPS=env.constants.stencilOps;check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)}));function read(name){check$1.optional((function(){env.assert(scope,'!("'+name+'" in '+value+")||"+"("+value+"."+name+" in "+STENCIL_OPS+")","invalid "+prop+"."+name+", must be one of "+Object.keys(stencilOps))}));return scope.def('"',name,'" in ',value,"?",STENCIL_OPS,"[",value,".",name,"]:",GL_KEEP)}return[prop===S_STENCIL_OPBACK?GL_BACK:GL_FRONT,read("fail"),read("zfail"),read("zpass")]}));case S_POLYGON_OFFSET_OFFSET:return parseParam((function(value){check$1.commandType(value,"object",param,env.commandStr);var factor=value.factor|0;var units=value.units|0;check$1.commandType(factor,"number",param+".factor",env.commandStr);check$1.commandType(units,"number",param+".units",env.commandStr);return[factor,units]}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid "+prop)}));var FACTOR=scope.def(value,".factor|0");var UNITS=scope.def(value,".units|0");return[FACTOR,UNITS]}));case S_CULL_FACE:return parseParam((function(value){var face=0;if(value==="front"){face=GL_FRONT}else if(value==="back"){face=GL_BACK}check$1.command(!!face,param,env.commandStr);return face}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,value+'==="front"||'+value+'==="back"',"invalid cull.face")}));return scope.def(value,'==="front"?',GL_FRONT,":",GL_BACK)}));case S_LINE_WIDTH:return parseParam((function(value){check$1.command(typeof value==="number"&&value>=limits.lineWidthDims[0]&&value<=limits.lineWidthDims[1],"invalid line width, must be a positive number between "+limits.lineWidthDims[0]+" and "+limits.lineWidthDims[1],env.commandStr);return value}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,"typeof "+value+'==="number"&&'+value+">="+limits.lineWidthDims[0]+"&&"+value+"<="+limits.lineWidthDims[1],"invalid line width")}));return value}));case S_FRONT_FACE:return parseParam((function(value){check$1.commandParameter(value,orientationType,param,env.commandStr);return orientationType[value]}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,value+'==="cw"||'+value+'==="ccw"',"invalid frontFace, must be one of cw,ccw")}));return scope.def(value+'==="cw"?'+GL_CW+":"+GL_CCW)}));case S_COLOR_MASK:return parseParam((function(value){check$1.command(isArrayLike(value)&&value.length===4,"color.mask must be length 4 array",env.commandStr);return value.map((function(v){return!!v}))}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,env.shared.isArrayLike+"("+value+")&&"+value+".length===4","invalid color.mask")}));return loop(4,(function(i){return"!!"+value+"["+i+"]"}))}));case S_SAMPLE_COVERAGE:return parseParam((function(value){check$1.command(typeof value==="object"&&value,param,env.commandStr);var sampleValue="value"in value?value.value:1;var sampleInvert=!!value.invert;check$1.command(typeof sampleValue==="number"&&sampleValue>=0&&sampleValue<=1,"sample.coverage.value must be a number between 0 and 1",env.commandStr);return[sampleValue,sampleInvert]}),(function(env,scope,value){check$1.optional((function(){env.assert(scope,value+"&&typeof "+value+'==="object"',"invalid sample.coverage")}));var VALUE=scope.def('"value" in ',value,"?+",value,".value:1");var INVERT=scope.def("!!",value,".invert");return[VALUE,INVERT]}))}}));return STATE}function parseUniforms(uniforms,env){var staticUniforms=uniforms.static;var dynamicUniforms=uniforms.dynamic;var UNIFORMS={};Object.keys(staticUniforms).forEach((function(name){var value=staticUniforms[name];var result;if(typeof value==="number"||typeof value==="boolean"){result=createStaticDecl((function(){return value}))}else if(typeof value==="function"){var reglType=value._reglType;if(reglType==="texture2d"||reglType==="textureCube"){result=createStaticDecl((function(env){return env.link(value)}))}else if(reglType==="framebuffer"||reglType==="framebufferCube"){check$1.command(value.color.length>0,'missing color attachment for framebuffer sent to uniform "'+name+'"',env.commandStr);result=createStaticDecl((function(env){return env.link(value.color[0])}))}else{check$1.commandRaise('invalid data for uniform "'+name+'"',env.commandStr)}}else if(isArrayLike(value)){result=createStaticDecl((function(env){var ITEM=env.global.def("[",loop(value.length,(function(i){check$1.command(typeof value[i]==="number"||typeof value[i]==="boolean","invalid uniform "+name,env.commandStr);return value[i]})),"]");return ITEM}))}else{check$1.commandRaise('invalid or missing data for uniform "'+name+'"',env.commandStr)}result.value=value;UNIFORMS[name]=result}));Object.keys(dynamicUniforms).forEach((function(key){var dyn=dynamicUniforms[key];UNIFORMS[key]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))}));return UNIFORMS}function parseAttributes(attributes,env){var staticAttributes=attributes.static;var dynamicAttributes=attributes.dynamic;var attributeDefs={};Object.keys(staticAttributes).forEach((function(attribute){var value=staticAttributes[attribute];var id=stringStore.id(attribute);var record=new AttributeRecord;if(isBufferArgs(value)){record.state=ATTRIB_STATE_POINTER;record.buffer=bufferState.getBuffer(bufferState.create(value,GL_ARRAY_BUFFER$2,false,true));record.type=0}else{var buffer=bufferState.getBuffer(value);if(buffer){record.state=ATTRIB_STATE_POINTER;record.buffer=buffer;record.type=0}else{check$1.command(typeof value==="object"&&value,"invalid data for attribute "+attribute,env.commandStr);if("constant"in value){var constant=value.constant;record.buffer="null";record.state=ATTRIB_STATE_CONSTANT;if(typeof constant==="number"){record.x=constant}else{check$1.command(isArrayLike(constant)&&constant.length>0&&constant.length<=4,"invalid constant for attribute "+attribute,env.commandStr);CUTE_COMPONENTS.forEach((function(c,i){if(i=0,'invalid offset for attribute "'+attribute+'"',env.commandStr);var stride=value.stride|0;check$1.command(stride>=0&&stride<256,'invalid stride for attribute "'+attribute+'", must be integer betweeen [0, 255]',env.commandStr);var size=value.size|0;check$1.command(!("size"in value)||size>0&&size<=4,'invalid size for attribute "'+attribute+'", must be 1,2,3,4',env.commandStr);var normalized=!!value.normalized;var type=0;if("type"in value){check$1.commandParameter(value.type,glTypes,"invalid type for attribute "+attribute,env.commandStr);type=glTypes[value.type]}var divisor=value.divisor|0;if("divisor"in value){check$1.command(divisor===0||extInstancing,'cannot specify divisor for attribute "'+attribute+'", instancing not supported',env.commandStr);check$1.command(divisor>=0,'invalid divisor for attribute "'+attribute+'"',env.commandStr)}check$1.optional((function(){var command=env.commandStr;var VALID_KEYS=["buffer","offset","divisor","normalized","type","size","stride"];Object.keys(value).forEach((function(prop){check$1.command(VALID_KEYS.indexOf(prop)>=0,'unknown parameter "'+prop+'" for attribute pointer "'+attribute+'" (valid parameters are '+VALID_KEYS+")",command)}))}));record.buffer=buffer;record.state=ATTRIB_STATE_POINTER;record.size=size;record.normalized=normalized;record.type=type||buffer.dtype;record.offset=offset;record.stride=stride;record.divisor=divisor}}}attributeDefs[attribute]=createStaticDecl((function(env,scope){var cache=env.attribCache;if(id in cache){return cache[id]}var result={isStream:false};Object.keys(record).forEach((function(key){result[key]=record[key]}));if(record.buffer){result.buffer=env.link(record.buffer);result.type=result.type||result.buffer+".dtype"}cache[id]=result;return result}))}));Object.keys(dynamicAttributes).forEach((function(attribute){var dyn=dynamicAttributes[attribute];function appendAttributeCode(env,block){var VALUE=env.invoke(block,dyn);var shared=env.shared;var constants=env.constants;var IS_BUFFER_ARGS=shared.isBufferArgs;var BUFFER_STATE=shared.buffer;check$1.optional((function(){env.assert(block,VALUE+"&&(typeof "+VALUE+'==="object"||typeof '+VALUE+'==="function")&&('+IS_BUFFER_ARGS+"("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+")||"+BUFFER_STATE+".getBuffer("+VALUE+".buffer)||"+IS_BUFFER_ARGS+"("+VALUE+".buffer)||"+'("constant" in '+VALUE+"&&(typeof "+VALUE+'.constant==="number"||'+shared.isArrayLike+"("+VALUE+".constant))))",'invalid dynamic attribute "'+attribute+'"')}));var result={isStream:block.def(false)};var defaultRecord=new AttributeRecord;defaultRecord.state=ATTRIB_STATE_POINTER;Object.keys(defaultRecord).forEach((function(key){result[key]=block.def(""+defaultRecord[key])}));var BUFFER=result.buffer;var TYPE=result.type;block("if(",IS_BUFFER_ARGS,"(",VALUE,")){",result.isStream,"=true;",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,");",TYPE,"=",BUFFER,".dtype;","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,");","if(",BUFFER,"){",TYPE,"=",BUFFER,".dtype;",'}else if("constant" in ',VALUE,"){",result.state,"=",ATTRIB_STATE_CONSTANT,";","if(typeof "+VALUE+'.constant === "number"){',result[CUTE_COMPONENTS[0]],"=",VALUE,".constant;",CUTE_COMPONENTS.slice(1).map((function(n){return result[n]})).join("="),"=0;","}else{",CUTE_COMPONENTS.map((function(name,i){return result[name]+"="+VALUE+".constant.length>"+i+"?"+VALUE+".constant["+i+"]:0;"})).join(""),"}}else{","if(",IS_BUFFER_ARGS,"(",VALUE,".buffer)){",BUFFER,"=",BUFFER_STATE,".createStream(",GL_ARRAY_BUFFER$2,",",VALUE,".buffer);","}else{",BUFFER,"=",BUFFER_STATE,".getBuffer(",VALUE,".buffer);","}",TYPE,'="type" in ',VALUE,"?",constants.glTypes,"[",VALUE,".type]:",BUFFER,".dtype;",result.normalized,"=!!",VALUE,".normalized;");function emitReadRecord(name){block(result[name],"=",VALUE,".",name,"|0;")}emitReadRecord("size");emitReadRecord("offset");emitReadRecord("stride");emitReadRecord("divisor");block("}}");block.exit("if(",result.isStream,"){",BUFFER_STATE,".destroyStream(",BUFFER,");","}");return result}attributeDefs[attribute]=createDynamicDecl(dyn,appendAttributeCode)}));return attributeDefs}function parseVAO(options,env){var staticOptions=options.static;var dynamicOptions=options.dynamic;if(S_VAO in staticOptions){var vao=staticOptions[S_VAO];if(vao!==null&&attributeState.getVAO(vao)===null){vao=attributeState.createVAO(vao)}return createStaticDecl((function(env){return env.link(attributeState.getVAO(vao))}))}else if(S_VAO in dynamicOptions){var dyn=dynamicOptions[S_VAO];return createDynamicDecl(dyn,(function(env,scope){var vaoRef=env.invoke(scope,dyn);return scope.def(env.shared.vao+".getVAO("+vaoRef+")")}))}return null}function parseContext(context){var staticContext=context.static;var dynamicContext=context.dynamic;var result={};Object.keys(staticContext).forEach((function(name){var value=staticContext[name];result[name]=createStaticDecl((function(env,scope){if(typeof value==="number"||typeof value==="boolean"){return""+value}else{return env.link(value)}}))}));Object.keys(dynamicContext).forEach((function(name){var dyn=dynamicContext[name];result[name]=createDynamicDecl(dyn,(function(env,scope){return env.invoke(scope,dyn)}))}));return result}function parseArguments(options,attributes,uniforms,context,env){var staticOptions=options.static;var dynamicOptions=options.dynamic;check$1.optional((function(){var KEY_NAMES=[S_FRAMEBUFFER,S_VERT,S_FRAG,S_ELEMENTS,S_PRIMITIVE,S_OFFSET,S_COUNT,S_INSTANCES,S_PROFILE,S_VAO].concat(GL_STATE_NAMES);function checkKeys(dict){Object.keys(dict).forEach((function(key){check$1.command(KEY_NAMES.indexOf(key)>=0,'unknown parameter "'+key+'"',env.commandStr)}))}checkKeys(staticOptions);checkKeys(dynamicOptions)}));var attribLocations=parseAttribLocations(options,attributes);var framebuffer=parseFramebuffer(options,env);var viewportAndScissor=parseViewportScissor(options,framebuffer,env);var draw=parseDraw(options,env);var state=parseGLState(options,env);var shader=parseProgram(options,env,attribLocations);function copyBox(name){var defn=viewportAndScissor[name];if(defn){state[name]=defn}}copyBox(S_VIEWPORT);copyBox(propName(S_SCISSOR_BOX));var dirty=Object.keys(state).length>0;var result={framebuffer:framebuffer,draw:draw,shader:shader,state:state,dirty:dirty,scopeVAO:null,drawVAO:null,useVAO:false,attributes:{}};result.profile=parseProfile(options,env);result.uniforms=parseUniforms(uniforms,env);result.drawVAO=result.scopeVAO=parseVAO(options,env);if(!result.drawVAO&&shader.program&&!attribLocations&&extensions.angle_instanced_arrays){var useVAO=true;var staticBindings=shader.program.attributes.map((function(attr){var binding=attributes.static[attr];useVAO=useVAO&&!!binding;return binding}));if(useVAO&&staticBindings.length>0){var vao=attributeState.getVAO(attributeState.createVAO(staticBindings));result.drawVAO=new Declaration(null,null,null,(function(env,scope){return env.link(vao)}));result.useVAO=true}}if(attribLocations){result.useVAO=true}else{result.attributes=parseAttributes(attributes,env)}result.context=parseContext(context,env);return result}function emitContext(env,scope,context){var shared=env.shared;var CONTEXT=shared.context;var contextEnter=env.scope();Object.keys(context).forEach((function(name){scope.save(CONTEXT,"."+name);var defn=context[name];var value=defn.append(env,scope);if(Array.isArray(value)){contextEnter(CONTEXT,".",name,"=[",value.join(),"];")}else{contextEnter(CONTEXT,".",name,"=",value,";")}}));scope(contextEnter)}function emitPollFramebuffer(env,scope,framebuffer,skipCheck){var shared=env.shared;var GL=shared.gl;var FRAMEBUFFER_STATE=shared.framebuffer;var EXT_DRAW_BUFFERS;if(extDrawBuffers){EXT_DRAW_BUFFERS=scope.def(shared.extensions,".webgl_draw_buffers")}var constants=env.constants;var DRAW_BUFFERS=constants.drawBuffer;var BACK_BUFFER=constants.backBuffer;var NEXT;if(framebuffer){NEXT=framebuffer.append(env,scope)}else{NEXT=scope.def(FRAMEBUFFER_STATE,".next")}if(!skipCheck){scope("if(",NEXT,"!==",FRAMEBUFFER_STATE,".cur){")}scope("if(",NEXT,"){",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",",NEXT,".framebuffer);");if(extDrawBuffers){scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",DRAW_BUFFERS,"[",NEXT,".colorAttachments.length]);")}scope("}else{",GL,".bindFramebuffer(",GL_FRAMEBUFFER$2,",null);");if(extDrawBuffers){scope(EXT_DRAW_BUFFERS,".drawBuffersWEBGL(",BACK_BUFFER,");")}scope("}",FRAMEBUFFER_STATE,".cur=",NEXT,";");if(!skipCheck){scope("}")}}function emitPollState(env,scope,args){var shared=env.shared;var GL=shared.gl;var CURRENT_VARS=env.current;var NEXT_VARS=env.next;var CURRENT_STATE=shared.current;var NEXT_STATE=shared.next;var block=env.cond(CURRENT_STATE,".dirty");GL_STATE_NAMES.forEach((function(prop){var param=propName(prop);if(param in args.state){return}var NEXT,CURRENT;if(param in NEXT_VARS){NEXT=NEXT_VARS[param];CURRENT=CURRENT_VARS[param];var parts=loop(currentState[param].length,(function(i){return block.def(NEXT,"[",i,"]")}));block(env.cond(parts.map((function(p,i){return p+"!=="+CURRENT+"["+i+"]"})).join("||")).then(GL,".",GL_VARIABLES[param],"(",parts,");",parts.map((function(p,i){return CURRENT+"["+i+"]="+p})).join(";"),";"))}else{NEXT=block.def(NEXT_STATE,".",param);var ifte=env.cond(NEXT,"!==",CURRENT_STATE,".",param);block(ifte);if(param in GL_FLAGS){ifte(env.cond(NEXT).then(GL,".enable(",GL_FLAGS[param],");").else(GL,".disable(",GL_FLAGS[param],");"),CURRENT_STATE,".",param,"=",NEXT,";")}else{ifte(GL,".",GL_VARIABLES[param],"(",NEXT,");",CURRENT_STATE,".",param,"=",NEXT,";")}}}));if(Object.keys(args.state).length===0){block(CURRENT_STATE,".dirty=false;")}scope(block)}function emitSetOptions(env,scope,options,filter){var shared=env.shared;var CURRENT_VARS=env.current;var CURRENT_STATE=shared.current;var GL=shared.gl;sortState(Object.keys(options)).forEach((function(param){var defn=options[param];if(filter&&!filter(defn)){return}var variable=defn.append(env,scope);if(GL_FLAGS[param]){var flag=GL_FLAGS[param];if(isStatic(defn)){if(variable){scope(GL,".enable(",flag,");")}else{scope(GL,".disable(",flag,");")}}else{scope(env.cond(variable).then(GL,".enable(",flag,");").else(GL,".disable(",flag,");"))}scope(CURRENT_STATE,".",param,"=",variable,";")}else if(isArrayLike(variable)){var CURRENT=CURRENT_VARS[param];scope(GL,".",GL_VARIABLES[param],"(",variable,");",variable.map((function(v,i){return CURRENT+"["+i+"]="+v})).join(";"),";")}else{scope(GL,".",GL_VARIABLES[param],"(",variable,");",CURRENT_STATE,".",param,"=",variable,";")}}))}function injectExtensions(env,scope){if(extInstancing){env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays")}}function emitProfile(env,scope,args,useScope,incrementCounter){var shared=env.shared;var STATS=env.stats;var CURRENT_STATE=shared.current;var TIMER=shared.timer;var profileArg=args.profile;function perfCounter(){if(typeof performance==="undefined"){return"Date.now()"}else{return"performance.now()"}}var CPU_START,QUERY_COUNTER;function emitProfileStart(block){CPU_START=scope.def();block(CPU_START,"=",perfCounter(),";");if(typeof incrementCounter==="string"){block(STATS,".count+=",incrementCounter,";")}else{block(STATS,".count++;")}if(timer){if(useScope){QUERY_COUNTER=scope.def();block(QUERY_COUNTER,"=",TIMER,".getNumPendingQueries();")}else{block(TIMER,".beginQuery(",STATS,");")}}}function emitProfileEnd(block){block(STATS,".cpuTime+=",perfCounter(),"-",CPU_START,";");if(timer){if(useScope){block(TIMER,".pushScopeStats(",QUERY_COUNTER,",",TIMER,".getNumPendingQueries(),",STATS,");")}else{block(TIMER,".endQuery();")}}}function scopeProfile(value){var prev=scope.def(CURRENT_STATE,".profile");scope(CURRENT_STATE,".profile=",value,";");scope.exit(CURRENT_STATE,".profile=",prev,";")}var USE_PROFILE;if(profileArg){if(isStatic(profileArg)){if(profileArg.enable){emitProfileStart(scope);emitProfileEnd(scope.exit);scopeProfile("true")}else{scopeProfile("false")}return}USE_PROFILE=profileArg.append(env,scope);scopeProfile(USE_PROFILE)}else{USE_PROFILE=scope.def(CURRENT_STATE,".profile")}var start=env.block();emitProfileStart(start);scope("if(",USE_PROFILE,"){",start,"}");var end=env.block();emitProfileEnd(end);scope.exit("if(",USE_PROFILE,"){",end,"}")}function emitAttributes(env,scope,args,attributes,filter){var shared=env.shared;function typeLength(x){switch(x){case GL_FLOAT_VEC2:case GL_INT_VEC2:case GL_BOOL_VEC2:return 2;case GL_FLOAT_VEC3:case GL_INT_VEC3:case GL_BOOL_VEC3:return 3;case GL_FLOAT_VEC4:case GL_INT_VEC4:case GL_BOOL_VEC4:return 4;default:return 1}}function emitBindAttribute(ATTRIBUTE,size,record){var GL=shared.gl;var LOCATION=scope.def(ATTRIBUTE,".location");var BINDING=scope.def(shared.attributes,"[",LOCATION,"]");var STATE=record.state;var BUFFER=record.buffer;var CONST_COMPONENTS=[record.x,record.y,record.z,record.w];var COMMON_KEYS=["buffer","normalized","offset","stride"];function emitBuffer(){scope("if(!",BINDING,".buffer){",GL,".enableVertexAttribArray(",LOCATION,");}");var TYPE=record.type;var SIZE;if(!record.size){SIZE=size}else{SIZE=scope.def(record.size,"||",size)}scope("if(",BINDING,".type!==",TYPE,"||",BINDING,".size!==",SIZE,"||",COMMON_KEYS.map((function(key){return BINDING+"."+key+"!=="+record[key]})).join("||"),"){",GL,".bindBuffer(",GL_ARRAY_BUFFER$2,",",BUFFER,".buffer);",GL,".vertexAttribPointer(",[LOCATION,SIZE,TYPE,record.normalized,record.stride,record.offset],");",BINDING,".type=",TYPE,";",BINDING,".size=",SIZE,";",COMMON_KEYS.map((function(key){return BINDING+"."+key+"="+record[key]+";"})).join(""),"}");if(extInstancing){var DIVISOR=record.divisor;scope("if(",BINDING,".divisor!==",DIVISOR,"){",env.instancing,".vertexAttribDivisorANGLE(",[LOCATION,DIVISOR],");",BINDING,".divisor=",DIVISOR,";}")}}function emitConstant(){scope("if(",BINDING,".buffer){",GL,".disableVertexAttribArray(",LOCATION,");",BINDING,".buffer=null;","}if(",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"!=="+CONST_COMPONENTS[i]})).join("||"),"){",GL,".vertexAttrib4f(",LOCATION,",",CONST_COMPONENTS,");",CUTE_COMPONENTS.map((function(c,i){return BINDING+"."+c+"="+CONST_COMPONENTS[i]+";"})).join(""),"}")}if(STATE===ATTRIB_STATE_POINTER){emitBuffer()}else if(STATE===ATTRIB_STATE_CONSTANT){emitConstant()}else{scope("if(",STATE,"===",ATTRIB_STATE_POINTER,"){");emitBuffer();scope("}else{");emitConstant();scope("}")}}attributes.forEach((function(attribute){var name=attribute.name;var arg=args.attributes[name];var record;if(arg){if(!filter(arg)){return}record=arg.append(env,scope)}else{if(!filter(SCOPE_DECL)){return}var scopeAttrib=env.scopeAttrib(name);check$1.optional((function(){env.assert(scope,scopeAttrib+".state","missing attribute "+name)}));record={};Object.keys(new AttributeRecord).forEach((function(key){record[key]=scope.def(scopeAttrib,".",key)}))}emitBindAttribute(env.link(attribute),typeLength(attribute.info.type),record)}))}function emitUniforms(env,scope,args,uniforms,filter){var shared=env.shared;var GL=shared.gl;var infix;for(var i=0;i1){scope(loop(unroll,(function(i){return Array.isArray(VALUE)?VALUE[i]:VALUE+"["+i+"]"})))}else{check$1(!Array.isArray(VALUE),"uniform value must not be an array");scope(VALUE)}scope(");")}}function emitDraw(env,outer,inner,args){var shared=env.shared;var GL=shared.gl;var DRAW_STATE=shared.draw;var drawOptions=args.draw;function emitElements(){var defn=drawOptions.elements;var ELEMENTS;var scope=outer;if(defn){if(defn.contextDep&&args.contextDynamic||defn.propDep){scope=inner}ELEMENTS=defn.append(env,scope)}else{ELEMENTS=scope.def(DRAW_STATE,".",S_ELEMENTS)}if(ELEMENTS){scope("if("+ELEMENTS+")"+GL+".bindBuffer("+GL_ELEMENT_ARRAY_BUFFER$1+","+ELEMENTS+".buffer.buffer);")}return ELEMENTS}function emitCount(){var defn=drawOptions.count;var COUNT;var scope=outer;if(defn){if(defn.contextDep&&args.contextDynamic||defn.propDep){scope=inner}COUNT=defn.append(env,scope);check$1.optional((function(){if(defn.MISSING){env.assert(outer,"false","missing vertex count")}if(defn.DYNAMIC){env.assert(scope,COUNT+">=0","missing vertex count")}}))}else{COUNT=scope.def(DRAW_STATE,".",S_COUNT);check$1.optional((function(){env.assert(scope,COUNT+">=0","missing vertex count")}))}return COUNT}var ELEMENTS=emitElements();function emitValue(name){var defn=drawOptions[name];if(defn){if(defn.contextDep&&args.contextDynamic||defn.propDep){return defn.append(env,inner)}else{return defn.append(env,outer)}}else{return outer.def(DRAW_STATE,".",name)}}var PRIMITIVE=emitValue(S_PRIMITIVE);var OFFSET=emitValue(S_OFFSET);var COUNT=emitCount();if(typeof COUNT==="number"){if(COUNT===0){return}}else{inner("if(",COUNT,"){");inner.exit("}")}var INSTANCES,EXT_INSTANCING;if(extInstancing){INSTANCES=emitValue(S_INSTANCES);EXT_INSTANCING=env.instancing}var ELEMENT_TYPE=ELEMENTS+".type";var elementsStatic=drawOptions.elements&&isStatic(drawOptions.elements);function emitInstancing(){function drawElements(){inner(EXT_INSTANCING,".drawElementsInstancedANGLE(",[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)",INSTANCES],");")}function drawArrays(){inner(EXT_INSTANCING,".drawArraysInstancedANGLE(",[PRIMITIVE,OFFSET,COUNT,INSTANCES],");")}if(ELEMENTS){if(!elementsStatic){inner("if(",ELEMENTS,"){");drawElements();inner("}else{");drawArrays();inner("}")}else{drawElements()}}else{drawArrays()}}function emitRegular(){function drawElements(){inner(GL+".drawElements("+[PRIMITIVE,COUNT,ELEMENT_TYPE,OFFSET+"<<(("+ELEMENT_TYPE+"-"+GL_UNSIGNED_BYTE$8+")>>1)"]+");")}function drawArrays(){inner(GL+".drawArrays("+[PRIMITIVE,OFFSET,COUNT]+");")}if(ELEMENTS){if(!elementsStatic){inner("if(",ELEMENTS,"){");drawElements();inner("}else{");drawArrays();inner("}")}else{drawElements()}}else{drawArrays()}}if(extInstancing&&(typeof INSTANCES!=="number"||INSTANCES>=0)){if(typeof INSTANCES==="string"){inner("if(",INSTANCES,">0){");emitInstancing();inner("}else if(",INSTANCES,"<0){");emitRegular();inner("}")}else{emitInstancing()}}else{emitRegular()}}function createBody(emitBody,parentEnv,args,program,count){var env=createREGLEnvironment();var scope=env.proc("body",count);check$1.optional((function(){env.commandStr=parentEnv.commandStr;env.command=env.link(parentEnv.commandStr)}));if(extInstancing){env.instancing=scope.def(env.shared.extensions,".angle_instanced_arrays")}emitBody(env,scope,args,program);return env.compile().body}function emitDrawBody(env,draw,args,program){injectExtensions(env,draw);if(args.useVAO){if(args.drawVAO){draw(env.shared.vao,".setVAO(",args.drawVAO.append(env,draw),");")}else{draw(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);")}}else{draw(env.shared.vao,".setVAO(null);");emitAttributes(env,draw,args,program.attributes,(function(){return true}))}emitUniforms(env,draw,args,program.uniforms,(function(){return true}));emitDraw(env,draw,draw,args)}function emitDrawProc(env,args){var draw=env.proc("draw",1);injectExtensions(env,draw);emitContext(env,draw,args.context);emitPollFramebuffer(env,draw,args.framebuffer);emitPollState(env,draw,args);emitSetOptions(env,draw,args.state);emitProfile(env,draw,args,false,true);var program=args.shader.progVar.append(env,draw);draw(env.shared.gl,".useProgram(",program,".program);");if(args.shader.program){emitDrawBody(env,draw,args,args.shader.program)}else{draw(env.shared.vao,".setVAO(null);");var drawCache=env.global.def("{}");var PROG_ID=draw.def(program,".id");var CACHED_PROC=draw.def(drawCache,"[",PROG_ID,"]");draw(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0);").else(CACHED_PROC,"=",drawCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitDrawBody,env,args,program,1)})),"(",program,");",CACHED_PROC,".call(this,a0);"))}if(Object.keys(args.state).length>0){draw(env.shared.current,".dirty=true;")}}function emitBatchDynamicShaderBody(env,scope,args,program){env.batchId="a1";injectExtensions(env,scope);function all(){return true}emitAttributes(env,scope,args,program.attributes,all);emitUniforms(env,scope,args,program.uniforms,all);emitDraw(env,scope,scope,args)}function emitBatchBody(env,scope,args,program){injectExtensions(env,scope);var contextDynamic=args.contextDep;var BATCH_ID=scope.def();var PROP_LIST="a0";var NUM_PROPS="a1";var PROPS=scope.def();env.shared.props=PROPS;env.batchId=BATCH_ID;var outer=env.scope();var inner=env.scope();scope(outer.entry,"for(",BATCH_ID,"=0;",BATCH_ID,"<",NUM_PROPS,";++",BATCH_ID,"){",PROPS,"=",PROP_LIST,"[",BATCH_ID,"];",inner,"}",outer.exit);function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}function isOuterDefn(defn){return!isInnerDefn(defn)}if(args.needsContext){emitContext(env,inner,args.context)}if(args.needsFramebuffer){emitPollFramebuffer(env,inner,args.framebuffer)}emitSetOptions(env,inner,args.state,isInnerDefn);if(args.profile&&isInnerDefn(args.profile)){emitProfile(env,inner,args,false,true)}if(!program){var progCache=env.global.def("{}");var PROGRAM=args.shader.progVar.append(env,inner);var PROG_ID=inner.def(PROGRAM,".id");var CACHED_PROC=inner.def(progCache,"[",PROG_ID,"]");inner(env.shared.gl,".useProgram(",PROGRAM,".program);","if(!",CACHED_PROC,"){",CACHED_PROC,"=",progCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchDynamicShaderBody,env,args,program,2)})),"(",PROGRAM,");}",CACHED_PROC,".call(this,a0[",BATCH_ID,"],",BATCH_ID,");")}else{if(args.useVAO){if(args.drawVAO){if(isInnerDefn(args.drawVAO)){inner(env.shared.vao,".setVAO(",args.drawVAO.append(env,inner),");")}else{outer(env.shared.vao,".setVAO(",args.drawVAO.append(env,outer),");")}}else{outer(env.shared.vao,".setVAO(",env.shared.vao,".targetVAO);")}}else{outer(env.shared.vao,".setVAO(null);");emitAttributes(env,outer,args,program.attributes,isOuterDefn);emitAttributes(env,inner,args,program.attributes,isInnerDefn)}emitUniforms(env,outer,args,program.uniforms,isOuterDefn);emitUniforms(env,inner,args,program.uniforms,isInnerDefn);emitDraw(env,outer,inner,args)}}function emitBatchProc(env,args){var batch=env.proc("batch",2);env.batchId="0";injectExtensions(env,batch);var contextDynamic=false;var needsContext=true;Object.keys(args.context).forEach((function(name){contextDynamic=contextDynamic||args.context[name].propDep}));if(!contextDynamic){emitContext(env,batch,args.context);needsContext=false}var framebuffer=args.framebuffer;var needsFramebuffer=false;if(framebuffer){if(framebuffer.propDep){contextDynamic=needsFramebuffer=true}else if(framebuffer.contextDep&&contextDynamic){needsFramebuffer=true}if(!needsFramebuffer){emitPollFramebuffer(env,batch,framebuffer)}}else{emitPollFramebuffer(env,batch,null)}if(args.state.viewport&&args.state.viewport.propDep){contextDynamic=true}function isInnerDefn(defn){return defn.contextDep&&contextDynamic||defn.propDep}emitPollState(env,batch,args);emitSetOptions(env,batch,args.state,(function(defn){return!isInnerDefn(defn)}));if(!args.profile||!isInnerDefn(args.profile)){emitProfile(env,batch,args,false,"a1")}args.contextDep=contextDynamic;args.needsContext=needsContext;args.needsFramebuffer=needsFramebuffer;var progDefn=args.shader.progVar;if(progDefn.contextDep&&contextDynamic||progDefn.propDep){emitBatchBody(env,batch,args,null)}else{var PROGRAM=progDefn.append(env,batch);batch(env.shared.gl,".useProgram(",PROGRAM,".program);");if(args.shader.program){emitBatchBody(env,batch,args,args.shader.program)}else{batch(env.shared.vao,".setVAO(null);");var batchCache=env.global.def("{}");var PROG_ID=batch.def(PROGRAM,".id");var CACHED_PROC=batch.def(batchCache,"[",PROG_ID,"]");batch(env.cond(CACHED_PROC).then(CACHED_PROC,".call(this,a0,a1);").else(CACHED_PROC,"=",batchCache,"[",PROG_ID,"]=",env.link((function(program){return createBody(emitBatchBody,env,args,program,2)})),"(",PROGRAM,");",CACHED_PROC,".call(this,a0,a1);"))}}if(Object.keys(args.state).length>0){batch(env.shared.current,".dirty=true;")}}function emitScopeProc(env,args){var scope=env.proc("scope",3);env.batchId="a2";var shared=env.shared;var CURRENT_STATE=shared.current;emitContext(env,scope,args.context);if(args.framebuffer){args.framebuffer.append(env,scope)}sortState(Object.keys(args.state)).forEach((function(name){var defn=args.state[name];var value=defn.append(env,scope);if(isArrayLike(value)){value.forEach((function(v,i){scope.set(env.next[name],"["+i+"]",v)}))}else{scope.set(shared.next,"."+name,value)}}));emitProfile(env,scope,args,true,true);[S_ELEMENTS,S_OFFSET,S_COUNT,S_INSTANCES,S_PRIMITIVE].forEach((function(opt){var variable=args.draw[opt];if(!variable){return}scope.set(shared.draw,"."+opt,""+variable.append(env,scope))}));Object.keys(args.uniforms).forEach((function(opt){var value=args.uniforms[opt].append(env,scope);if(Array.isArray(value)){value="["+value.join()+"]"}scope.set(shared.uniforms,"["+stringStore.id(opt)+"]",value)}));Object.keys(args.attributes).forEach((function(name){var record=args.attributes[name].append(env,scope);var scopeAttrib=env.scopeAttrib(name);Object.keys(new AttributeRecord).forEach((function(prop){scope.set(scopeAttrib,"."+prop,record[prop])}))}));if(args.scopeVAO){scope.set(shared.vao,".targetVAO",args.scopeVAO.append(env,scope))}function saveShader(name){var shader=args.shader[name];if(shader){scope.set(shared.shader,"."+name,shader.append(env,scope))}}saveShader(S_VERT);saveShader(S_FRAG);if(Object.keys(args.state).length>0){scope(CURRENT_STATE,".dirty=true;");scope.exit(CURRENT_STATE,".dirty=true;")}scope("a1(",env.shared.context,",a0,",env.batchId,");")}function isDynamicObject(object){if(typeof object!=="object"||isArrayLike(object)){return}var props=Object.keys(object);for(var i=0;i=0;--i){var cb=rafCallbacks[i];if(cb){cb(contextState,null,0)}}gl.flush();if(timer){timer.update()}}function startRAF(){if(!activeRAF&&rafCallbacks.length>0){activeRAF=raf.next(handleRAF)}}function stopRAF(){if(activeRAF){raf.cancel(handleRAF);activeRAF=null}}function handleContextLoss(event){event.preventDefault();contextLost=true;stopRAF();lossCallbacks.forEach((function(cb){cb()}))}function handleContextRestored(event){gl.getError();contextLost=false;extensionState.restore();shaderState.restore();bufferState.restore();textureState.restore();renderbufferState.restore();framebufferState.restore();attributeState.restore();if(timer){timer.restore()}core.procs.refresh();startRAF();restoreCallbacks.forEach((function(cb){cb()}))}if(canvas){canvas.addEventListener(CONTEXT_LOST_EVENT,handleContextLoss,false);canvas.addEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored,false)}function destroy(){rafCallbacks.length=0;stopRAF();if(canvas){canvas.removeEventListener(CONTEXT_LOST_EVENT,handleContextLoss);canvas.removeEventListener(CONTEXT_RESTORED_EVENT,handleContextRestored)}shaderState.clear();framebufferState.clear();renderbufferState.clear();textureState.clear();elementState.clear();bufferState.clear();attributeState.clear();if(timer){timer.clear()}destroyCallbacks.forEach((function(cb){cb()}))}function compileProcedure(options){check$1(!!options,"invalid args to regl({...})");check$1.type(options,"object","invalid args to regl({...})");function flattenNestedOptions(options){var result=extend({},options);delete result.uniforms;delete result.attributes;delete result.context;delete result.vao;if("stencil"in result&&result.stencil.op){result.stencil.opBack=result.stencil.opFront=result.stencil.op;delete result.stencil.op}function merge(name){if(name in result){var child=result[name];delete result[name];Object.keys(child).forEach((function(prop){result[name+"."+prop]=child[prop]}))}}merge("blend");merge("depth");merge("cull");merge("stencil");merge("polygonOffset");merge("scissor");merge("sample");if("vao"in options){result.vao=options.vao}return result}function separateDynamic(object,useArrays){var staticItems={};var dynamicItems={};Object.keys(object).forEach((function(option){var value=object[option];if(dynamic.isDynamic(value)){dynamicItems[option]=dynamic.unbox(value,option);return}else if(useArrays&&Array.isArray(value)){for(var i=0;i0){return batch.call(this,reserve(args|0),args|0)}}else if(Array.isArray(args)){if(args.length){return batch.call(this,args,args.length)}}else{return draw.call(this,args)}}return extend(REGLCommand,{stats:stats$$1,destroy:function(){compiled.destroy()}})}var setFBO=framebufferState.setFBO=compileProcedure({framebuffer:dynamic.define.call(null,DYN_PROP,"framebuffer")});function clearImpl(_,options){var clearFlags=0;core.procs.poll();var c=options.color;if(c){gl.clearColor(+c[0]||0,+c[1]||0,+c[2]||0,+c[3]||0);clearFlags|=GL_COLOR_BUFFER_BIT}if("depth"in options){gl.clearDepth(+options.depth);clearFlags|=GL_DEPTH_BUFFER_BIT}if("stencil"in options){gl.clearStencil(options.stencil|0);clearFlags|=GL_STENCIL_BUFFER_BIT}check$1(!!clearFlags,"called regl.clear with no buffer specified");gl.clear(clearFlags)}function clear(options){check$1(typeof options==="object"&&options,"regl.clear() takes an object as input");if("framebuffer"in options){if(options.framebuffer&&options.framebuffer_reglType==="framebufferCube"){for(var i=0;i<6;++i){setFBO(extend({framebuffer:options.framebuffer.faces[i]},options),clearImpl)}}else{setFBO(options,clearImpl)}}else{clearImpl(null,options)}}function frame(cb){check$1.type(cb,"function","regl.frame() callback must be a function");rafCallbacks.push(cb);function cancel(){var i=find(rafCallbacks,cb);check$1(i>=0,"cannot cancel a frame twice");function pendingCancel(){var index=find(rafCallbacks,pendingCancel);rafCallbacks[index]=rafCallbacks[rafCallbacks.length-1];rafCallbacks.length-=1;if(rafCallbacks.length<=0){stopRAF()}}rafCallbacks[i]=pendingCancel}startRAF();return{cancel:cancel}}function pollViewport(){var viewport=nextState.viewport;var scissorBox=nextState.scissor_box;viewport[0]=viewport[1]=scissorBox[0]=scissorBox[1]=0;contextState.viewportWidth=contextState.framebufferWidth=contextState.drawingBufferWidth=viewport[2]=scissorBox[2]=gl.drawingBufferWidth;contextState.viewportHeight=contextState.framebufferHeight=contextState.drawingBufferHeight=viewport[3]=scissorBox[3]=gl.drawingBufferHeight}function poll(){contextState.tick+=1;contextState.time=now();pollViewport();core.procs.poll()}function refresh(){textureState.refresh();pollViewport();core.procs.refresh();if(timer){timer.update()}}function now(){return(clock()-START_TIME)/1e3}refresh();function addListener(event,callback){check$1.type(callback,"function","listener callback must be a function");var callbacks;switch(event){case"frame":return frame(callback);case"lost":callbacks=lossCallbacks;break;case"restore":callbacks=restoreCallbacks;break;case"destroy":callbacks=destroyCallbacks;break;default:check$1.raise("invalid event, must be one of frame,lost,restore,destroy")}callbacks.push(callback);return{cancel:function(){for(var i=0;i=0},read:readPixels,destroy:destroy,_gl:gl,_refresh:refresh,poll:function(){poll();if(timer){timer.update()}},now:now,stats:stats$$1});config.onDone(null,regl);return regl}return wrapREGL}))},{}],185:[function(require,module,exports){"use strict";module.exports=function removeItems(arr,startIdx,removeCount){var i,length=arr.length;if(startIdx>=length||removeCount===0){return}removeCount=startIdx+removeCount>length?length-startIdx:removeCount;var len=length-removeCount;for(i=startIdx;i */ var buffer=require("buffer");var Buffer=buffer.Buffer;function copyProps(src,dst){for(var key in src){dst[key]=src[key]}}if(Buffer.from&&Buffer.alloc&&Buffer.allocUnsafe&&Buffer.allocUnsafeSlow){module.exports=buffer}else{copyProps(buffer,exports);exports.Buffer=SafeBuffer}function SafeBuffer(arg,encodingOrOffset,length){return Buffer(arg,encodingOrOffset,length)}SafeBuffer.prototype=Object.create(Buffer.prototype);copyProps(Buffer,SafeBuffer);SafeBuffer.from=function(arg,encodingOrOffset,length){if(typeof arg==="number"){throw new TypeError("Argument must not be a number")}return Buffer(arg,encodingOrOffset,length)};SafeBuffer.alloc=function(size,fill,encoding){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}var buf=Buffer(size);if(fill!==undefined){if(typeof encoding==="string"){buf.fill(fill,encoding)}else{buf.fill(fill)}}else{buf.fill(0)}return buf};SafeBuffer.allocUnsafe=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return Buffer(size)};SafeBuffer.allocUnsafeSlow=function(size){if(typeof size!=="number"){throw new TypeError("Argument must be a number")}return buffer.SlowBuffer(size)}},{buffer:32}],188:[function(require,module,exports){module.exports=scrollToAnchor;function scrollToAnchor(anchor,options){if(anchor){try{var el=document.querySelector(anchor);if(el)el.scrollIntoView(options)}catch(e){}}}},{}],189:[function(require,module,exports){"use strict";module.exports=require("./lib/index")},{"./lib/index":193}],190:[function(require,module,exports){"use strict";var randomFromSeed=require("./random/random-from-seed");var ORIGINAL="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-";var alphabet;var previousSeed;var shuffled;function reset(){shuffled=false}function setCharacters(_alphabet_){if(!_alphabet_){if(alphabet!==ORIGINAL){alphabet=ORIGINAL;reset()}return}if(_alphabet_===alphabet){return}if(_alphabet_.length!==ORIGINAL.length){throw new Error("Custom alphabet for shortid must be "+ORIGINAL.length+" unique characters. You submitted "+_alphabet_.length+" characters: "+_alphabet_)}var unique=_alphabet_.split("").filter((function(item,ind,arr){return ind!==arr.lastIndexOf(item)}));if(unique.length){throw new Error("Custom alphabet for shortid must be "+ORIGINAL.length+" unique characters. These characters were not unique: "+unique.join(", "))}alphabet=_alphabet_;reset()}function characters(_alphabet_){setCharacters(_alphabet_);return alphabet}function setSeed(seed){randomFromSeed.seed(seed);if(previousSeed!==seed){reset();previousSeed=seed}}function shuffle(){if(!alphabet){setCharacters(ORIGINAL)}var sourceArray=alphabet.split("");var targetArray=[];var r=randomFromSeed.nextValue();var characterIndex;while(sourceArray.length>0){r=randomFromSeed.nextValue();characterIndex=Math.floor(r*sourceArray.length);targetArray.push(sourceArray.splice(characterIndex,1)[0])}return targetArray.join("")}function getShuffled(){if(shuffled){return shuffled}shuffled=shuffle();return shuffled}function lookup(index){var alphabetShuffled=getShuffled();return alphabetShuffled[index]}function get(){return alphabet||ORIGINAL}module.exports={get:get,characters:characters,seed:setSeed,lookup:lookup,shuffled:getShuffled}},{"./random/random-from-seed":196}],191:[function(require,module,exports){"use strict";var generate=require("./generate");var alphabet=require("./alphabet");var REDUCE_TIME=1567752802062;var version=7;var counter;var previousSeconds;function build(clusterWorkerId){var str="";var seconds=Math.floor((Date.now()-REDUCE_TIME)*.001);if(seconds===previousSeconds){counter++}else{counter=0;previousSeconds=seconds}str=str+generate(version);str=str+generate(clusterWorkerId);if(counter>0){str=str+generate(counter)}str=str+generate(seconds);return str}module.exports=build},{"./alphabet":190,"./generate":192}],192:[function(require,module,exports){"use strict";var alphabet=require("./alphabet");var random=require("./random/random-byte");var format=require("nanoid/format");function generate(number){var loopCounter=0;var done;var str="";while(!done){str=str+format(random,alphabet.get(),1);done=number */ const debug=require("debug")("simple-peer");const getBrowserRTC=require("get-browser-rtc");const randombytes=require("randombytes");const stream=require("readable-stream");const queueMicrotask=require("queue-microtask");const errCode=require("err-code");const{Buffer:Buffer}=require("buffer");const MAX_BUFFERED_AMOUNT=64*1024;const ICECOMPLETE_TIMEOUT=5*1e3;const CHANNEL_CLOSING_TIMEOUT=5*1e3;function filterTrickle(sdp){return sdp.replace(/a=ice-options:trickle\s\n/g,"")}function warn(message){console.warn(message)}class Peer extends stream.Duplex{constructor(opts){opts=Object.assign({allowHalfOpen:false},opts);super(opts);this._id=randombytes(4).toString("hex").slice(0,7);this._debug("new peer %o",opts);this.channelName=opts.initiator?opts.channelName||randombytes(20).toString("hex"):null;this.initiator=opts.initiator||false;this.channelConfig=opts.channelConfig||Peer.channelConfig;this.channelNegotiated=this.channelConfig.negotiated;this.config=Object.assign({},Peer.config,opts.config);this.offerOptions=opts.offerOptions||{};this.answerOptions=opts.answerOptions||{};this.sdpTransform=opts.sdpTransform||(sdp=>sdp);this.streams=opts.streams||(opts.stream?[opts.stream]:[]);this.trickle=opts.trickle!==undefined?opts.trickle:true;this.allowHalfTrickle=opts.allowHalfTrickle!==undefined?opts.allowHalfTrickle:false;this.iceCompleteTimeout=opts.iceCompleteTimeout||ICECOMPLETE_TIMEOUT;this.destroyed=false;this.destroying=false;this._connected=false;this.remoteAddress=undefined;this.remoteFamily=undefined;this.remotePort=undefined;this.localAddress=undefined;this.localFamily=undefined;this.localPort=undefined;this._wrtc=opts.wrtc&&typeof opts.wrtc==="object"?opts.wrtc:getBrowserRTC();if(!this._wrtc){if(typeof window==="undefined"){throw errCode(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT")}else{throw errCode(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT")}}this._pcReady=false;this._channelReady=false;this._iceComplete=false;this._iceCompleteTimer=null;this._channel=null;this._pendingCandidates=[];this._isNegotiating=false;this._firstNegotiation=true;this._batchedNegotiation=false;this._queuedNegotiation=false;this._sendersAwaitingStable=[];this._senderMap=new Map;this._closingInterval=null;this._remoteTracks=[];this._remoteStreams=[];this._chunk=null;this._cb=null;this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(err){this.destroy(errCode(err,"ERR_PC_CONSTRUCTOR"));return}this._isReactNativeWebrtc=typeof this._pc._peerConnectionId==="number";this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()};this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()};this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()};this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()};this._pc.onicecandidate=event=>{this._onIceCandidate(event)};if(typeof this._pc.peerIdentity==="object"){this._pc.peerIdentity.catch((err=>{this.destroy(errCode(err,"ERR_PC_PEER_IDENTITY"))}))}if(this.initiator||this.channelNegotiated){this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)})}else{this._pc.ondatachannel=event=>{this._setupData(event)}}if(this.streams){this.streams.forEach((stream=>{this.addStream(stream)}))}this._pc.ontrack=event=>{this._onTrack(event)};this._debug("initial negotiation");this._needsNegotiation();this._onFinishBound=()=>{this._onFinish()};this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&this._channel.readyState==="open"}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(data){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if(typeof data==="string"){try{data=JSON.parse(data)}catch(err){data={}}}this._debug("signal()");if(data.renegotiate&&this.initiator){this._debug("got request to renegotiate");this._needsNegotiation()}if(data.transceiverRequest&&this.initiator){this._debug("got request for transceiver");this.addTransceiver(data.transceiverRequest.kind,data.transceiverRequest.init)}if(data.candidate){if(this._pc.remoteDescription&&this._pc.remoteDescription.type){this._addIceCandidate(data.candidate)}else{this._pendingCandidates.push(data.candidate)}}if(data.sdp){this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(data)).then((()=>{if(this.destroyed)return;this._pendingCandidates.forEach((candidate=>{this._addIceCandidate(candidate)}));this._pendingCandidates=[];if(this._pc.remoteDescription.type==="offer")this._createAnswer()})).catch((err=>{this.destroy(errCode(err,"ERR_SET_REMOTE_DESCRIPTION"))}))}if(!data.sdp&&!data.candidate&&!data.renegotiate&&!data.transceiverRequest){this.destroy(errCode(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(candidate){const iceCandidateObj=new this._wrtc.RTCIceCandidate(candidate);this._pc.addIceCandidate(iceCandidateObj).catch((err=>{if(!iceCandidateObj.address||iceCandidateObj.address.endsWith(".local")){warn("Ignoring unsupported ICE candidate.")}else{this.destroy(errCode(err,"ERR_ADD_ICE_CANDIDATE"))}}))}send(chunk){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(chunk)}addTransceiver(kind,init){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");this._debug("addTransceiver()");if(this.initiator){try{this._pc.addTransceiver(kind,init);this._needsNegotiation()}catch(err){this.destroy(errCode(err,"ERR_ADD_TRANSCEIVER"))}}else{this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:kind,init:init}})}}addStream(stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()");stream.getTracks().forEach((track=>{this.addTrack(track,stream)}))}addTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const submap=this._senderMap.get(track)||new Map;let sender=submap.get(stream);if(!sender){sender=this._pc.addTrack(track,stream);submap.set(stream,sender);this._senderMap.set(track,submap);this._needsNegotiation()}else if(sender.removed){throw errCode(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED")}else{throw errCode(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED")}}replaceTrack(oldTrack,newTrack,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const submap=this._senderMap.get(oldTrack);const sender=submap?submap.get(stream):null;if(!sender){throw errCode(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED")}if(newTrack)this._senderMap.set(newTrack,submap);if(sender.replaceTrack!=null){sender.replaceTrack(newTrack)}else{this.destroy(errCode(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}}removeTrack(track,stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const submap=this._senderMap.get(track);const sender=submap?submap.get(stream):null;if(!sender){throw errCode(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED")}try{sender.removed=true;this._pc.removeTrack(sender)}catch(err){if(err.name==="NS_ERROR_UNEXPECTED"){this._sendersAwaitingStable.push(sender)}else{this.destroy(errCode(err,"ERR_REMOVE_TRACK"))}}this._needsNegotiation()}removeStream(stream){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()");stream.getTracks().forEach((track=>{this.removeTrack(track,stream)}))}_needsNegotiation(){this._debug("_needsNegotiation");if(this._batchedNegotiation)return;this._batchedNegotiation=true;queueMicrotask((()=>{this._batchedNegotiation=false;if(this.initiator||!this._firstNegotiation){this._debug("starting batched negotiation");this.negotiate()}else{this._debug("non-initiator initial negotiation request discarded")}this._firstNegotiation=false}))}negotiate(){if(this.destroying)return;if(this.destroyed)throw errCode(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");if(this.initiator){if(this._isNegotiating){this._queuedNegotiation=true;this._debug("already negotiating, queueing")}else{this._debug("start negotiation");setTimeout((()=>{this._createOffer()}),0)}}else{if(this._isNegotiating){this._queuedNegotiation=true;this._debug("already negotiating, queueing")}else{this._debug("requesting negotiation from initiator");this.emit("signal",{type:"renegotiate",renegotiate:true})}}this._isNegotiating=true}destroy(err){this._destroy(err,(()=>{}))}_destroy(err,cb){if(this.destroyed||this.destroying)return;this.destroying=true;this._debug("destroying (error: %s)",err&&(err.message||err));queueMicrotask((()=>{this.destroyed=true;this.destroying=false;this._debug("destroy (error: %s)",err&&(err.message||err));this.readable=this.writable=false;if(!this._readableState.ended)this.push(null);if(!this._writableState.finished)this.end();this._connected=false;this._pcReady=false;this._channelReady=false;this._remoteTracks=null;this._remoteStreams=null;this._senderMap=null;clearInterval(this._closingInterval);this._closingInterval=null;clearInterval(this._interval);this._interval=null;this._chunk=null;this._cb=null;if(this._onFinishBound)this.removeListener("finish",this._onFinishBound);this._onFinishBound=null;if(this._channel){try{this._channel.close()}catch(err){}this._channel.onmessage=null;this._channel.onopen=null;this._channel.onclose=null;this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(err){}this._pc.oniceconnectionstatechange=null;this._pc.onicegatheringstatechange=null;this._pc.onsignalingstatechange=null;this._pc.onicecandidate=null;this._pc.ontrack=null;this._pc.ondatachannel=null}this._pc=null;this._channel=null;if(err)this.emit("error",err);this.emit("close");cb()}))}_setupData(event){if(!event.channel){return this.destroy(errCode(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"))}this._channel=event.channel;this._channel.binaryType="arraybuffer";if(typeof this._channel.bufferedAmountLowThreshold==="number"){this._channel.bufferedAmountLowThreshold=MAX_BUFFERED_AMOUNT}this.channelName=this._channel.label;this._channel.onmessage=event=>{this._onChannelMessage(event)};this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()};this._channel.onopen=()=>{this._onChannelOpen()};this._channel.onclose=()=>{this._onChannelClose()};this._channel.onerror=event=>{const err=event.error instanceof Error?event.error:new Error(`Datachannel error: ${event.message} ${event.filename}:${event.lineno}:${event.colno}`);this.destroy(errCode(err,"ERR_DATA_CHANNEL"))};let isClosing=false;this._closingInterval=setInterval((()=>{if(this._channel&&this._channel.readyState==="closing"){if(isClosing)this._onChannelClose();isClosing=true}else{isClosing=false}}),CHANNEL_CLOSING_TIMEOUT)}_read(){}_write(chunk,encoding,cb){if(this.destroyed)return cb(errCode(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}if(this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT){this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount);this._cb=cb}else{cb(null)}}else{this._debug("write before connect");this._chunk=chunk;this._cb=cb}}_onFinish(){if(this.destroyed)return;const destroySoon=()=>{setTimeout((()=>this.destroy()),1e3)};if(this._connected){destroySoon()}else{this.once("connect",destroySoon)}}_startIceCompleteTimeout(){if(this.destroyed)return;if(this._iceCompleteTimer)return;this._debug("started iceComplete timeout");this._iceCompleteTimer=setTimeout((()=>{if(!this._iceComplete){this._iceComplete=true;this._debug("iceComplete timeout completed");this.emit("iceTimeout");this.emit("_iceComplete")}}),this.iceCompleteTimeout)}_createOffer(){if(this.destroyed)return;this._pc.createOffer(this.offerOptions).then((offer=>{if(this.destroyed)return;if(!this.trickle&&!this.allowHalfTrickle)offer.sdp=filterTrickle(offer.sdp);offer.sdp=this.sdpTransform(offer.sdp);const sendOffer=()=>{if(this.destroyed)return;const signal=this._pc.localDescription||offer;this._debug("signal");this.emit("signal",{type:signal.type,sdp:signal.sdp})};const onSuccess=()=>{this._debug("createOffer success");if(this.destroyed)return;if(this.trickle||this._iceComplete)sendOffer();else this.once("_iceComplete",sendOffer)};const onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(offer).then(onSuccess).catch(onError)})).catch((err=>{this.destroy(errCode(err,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){if(this._pc.getTransceivers){this._pc.getTransceivers().forEach((transceiver=>{if(!transceiver.mid&&transceiver.sender.track&&!transceiver.requested){transceiver.requested=true;this.addTransceiver(transceiver.sender.track.kind)}}))}}_createAnswer(){if(this.destroyed)return;this._pc.createAnswer(this.answerOptions).then((answer=>{if(this.destroyed)return;if(!this.trickle&&!this.allowHalfTrickle)answer.sdp=filterTrickle(answer.sdp);answer.sdp=this.sdpTransform(answer.sdp);const sendAnswer=()=>{if(this.destroyed)return;const signal=this._pc.localDescription||answer;this._debug("signal");this.emit("signal",{type:signal.type,sdp:signal.sdp});if(!this.initiator)this._requestMissingTransceivers()};const onSuccess=()=>{if(this.destroyed)return;if(this.trickle||this._iceComplete)sendAnswer();else this.once("_iceComplete",sendAnswer)};const onError=err=>{this.destroy(errCode(err,"ERR_SET_LOCAL_DESCRIPTION"))};this._pc.setLocalDescription(answer).then(onSuccess).catch(onError)})).catch((err=>{this.destroy(errCode(err,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){if(this.destroyed)return;if(this._pc.connectionState==="failed"){this.destroy(errCode(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}}_onIceStateChange(){if(this.destroyed)return;const iceConnectionState=this._pc.iceConnectionState;const iceGatheringState=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState);this.emit("iceStateChange",iceConnectionState,iceGatheringState);if(iceConnectionState==="connected"||iceConnectionState==="completed"){this._pcReady=true;this._maybeReady()}if(iceConnectionState==="failed"){this.destroy(errCode(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE"))}if(iceConnectionState==="closed"){this.destroy(errCode(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}}getStats(cb){const flattenValues=report=>{if(Object.prototype.toString.call(report.values)==="[object Array]"){report.values.forEach((value=>{Object.assign(report,value)}))}return report};if(this._pc.getStats.length===0||this._isReactNativeWebrtc){this._pc.getStats().then((res=>{const reports=[];res.forEach((report=>{reports.push(flattenValues(report))}));cb(null,reports)}),(err=>cb(err)))}else if(this._pc.getStats.length>0){this._pc.getStats((res=>{if(this.destroyed)return;const reports=[];res.result().forEach((result=>{const report={};result.names().forEach((name=>{report[name]=result.stat(name)}));report.id=result.id;report.type=result.type;report.timestamp=result.timestamp;reports.push(flattenValues(report))}));cb(null,reports)}),(err=>cb(err)))}else{cb(null,[])}}_maybeReady(){this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady);if(this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=true;const findCandidatePair=()=>{if(this.destroyed)return;this.getStats(((err,items)=>{if(this.destroyed)return;if(err)items=[];const remoteCandidates={};const localCandidates={};const candidatePairs={};let foundSelectedCandidatePair=false;items.forEach((item=>{if(item.type==="remotecandidate"||item.type==="remote-candidate"){remoteCandidates[item.id]=item}if(item.type==="localcandidate"||item.type==="local-candidate"){localCandidates[item.id]=item}if(item.type==="candidatepair"||item.type==="candidate-pair"){candidatePairs[item.id]=item}}));const setSelectedCandidatePair=selectedCandidatePair=>{foundSelectedCandidatePair=true;let local=localCandidates[selectedCandidatePair.localCandidateId];if(local&&(local.ip||local.address)){this.localAddress=local.ip||local.address;this.localPort=Number(local.port)}else if(local&&local.ipAddress){this.localAddress=local.ipAddress;this.localPort=Number(local.portNumber)}else if(typeof selectedCandidatePair.googLocalAddress==="string"){local=selectedCandidatePair.googLocalAddress.split(":");this.localAddress=local[0];this.localPort=Number(local[1])}if(this.localAddress){this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4"}let remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];if(remote&&(remote.ip||remote.address)){this.remoteAddress=remote.ip||remote.address;this.remotePort=Number(remote.port)}else if(remote&&remote.ipAddress){this.remoteAddress=remote.ipAddress;this.remotePort=Number(remote.portNumber)}else if(typeof selectedCandidatePair.googRemoteAddress==="string"){remote=selectedCandidatePair.googRemoteAddress.split(":");this.remoteAddress=remote[0];this.remotePort=Number(remote[1])}if(this.remoteAddress){this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"}this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};items.forEach((item=>{if(item.type==="transport"&&item.selectedCandidatePairId){setSelectedCandidatePair(candidatePairs[item.selectedCandidatePairId])}if(item.type==="googCandidatePair"&&item.googActiveConnection==="true"||(item.type==="candidatepair"||item.type==="candidate-pair")&&item.selected){setSelectedCandidatePair(item)}}));if(!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length)){setTimeout(findCandidatePair,100);return}else{this._connecting=false;this._connected=true}if(this._chunk){try{this.send(this._chunk)}catch(err){return this.destroy(errCode(err,"ERR_DATA_CHANNEL"))}this._chunk=null;this._debug('sent chunk from "write before connect"');const cb=this._cb;this._cb=null;cb(null)}if(typeof this._channel.bufferedAmountLowThreshold!=="number"){this._interval=setInterval((()=>this._onInterval()),150);if(this._interval.unref)this._interval.unref()}this._debug("connect");this.emit("connect")}))};findCandidatePair()}_onInterval(){if(!this._cb||!this._channel||this._channel.bufferedAmount>MAX_BUFFERED_AMOUNT){return}this._onChannelBufferedAmountLow()}_onSignalingStateChange(){if(this.destroyed)return;if(this._pc.signalingState==="stable"){this._isNegotiating=false;this._debug("flushing sender queue",this._sendersAwaitingStable);this._sendersAwaitingStable.forEach((sender=>{this._pc.removeTrack(sender);this._queuedNegotiation=true}));this._sendersAwaitingStable=[];if(this._queuedNegotiation){this._debug("flushing negotiation queue");this._queuedNegotiation=false;this._needsNegotiation()}else{this._debug("negotiated");this.emit("negotiated")}}this._debug("signalingStateChange %s",this._pc.signalingState);this.emit("signalingStateChange",this._pc.signalingState)}_onIceCandidate(event){if(this.destroyed)return;if(event.candidate&&this.trickle){this.emit("signal",{type:"candidate",candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}})}else if(!event.candidate&&!this._iceComplete){this._iceComplete=true;this.emit("_iceComplete")}if(event.candidate){this._startIceCompleteTimeout()}}_onChannelMessage(event){if(this.destroyed)return;let data=event.data;if(data instanceof ArrayBuffer)data=Buffer.from(data);this.push(data)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const cb=this._cb;this._cb=null;cb(null)}_onChannelOpen(){if(this._connected||this.destroyed)return;this._debug("on channel open");this._channelReady=true;this._maybeReady()}_onChannelClose(){if(this.destroyed)return;this._debug("on channel close");this.destroy()}_onTrack(event){if(this.destroyed)return;event.streams.forEach((eventStream=>{this._debug("on track");this.emit("track",event.track,eventStream);this._remoteTracks.push({track:event.track,stream:eventStream});if(this._remoteStreams.some((remoteStream=>remoteStream.id===eventStream.id)))return;this._remoteStreams.push(eventStream);queueMicrotask((()=>{this._debug("on stream");this.emit("stream",eventStream)}))}))}_debug(){const args=[].slice.call(arguments);args[0]="["+this._id+"] "+args[0];debug.apply(null,args)}}Peer.WEBRTC_SUPPORT=!!getBrowserRTC();Peer.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"};Peer.channelConfig={};module.exports=Peer},{buffer:32,debug:200,"err-code":78,"get-browser-rtc":82,"queue-microtask":180,randombytes:183,"readable-stream":217}],200:[function(require,module,exports){(function(process){(function(){exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=localstorage();exports.destroy=(()=>{let warned=false;return()=>{if(!warned){warned=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(args){args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff);if(!this.useColors){return}const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0;let lastC=0;args[0].replace(/%[a-zA-Z%]/g,(match=>{if(match==="%%"){return}index++;if(match==="%c"){lastC=index}}));args.splice(lastC,0,c)}exports.log=console.debug||console.log||(()=>{});function save(namespaces){try{if(namespaces){exports.storage.setItem("debug",namespaces)}else{exports.storage.removeItem("debug")}}catch(error){}}function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}function localstorage(){try{return localStorage}catch(error){}}module.exports=require("./common")(exports);const{formatters:formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":201,_process:174}],201:[function(require,module,exports){arguments[4][72][0].apply(exports,arguments)},{dup:72,ms:202}],202:[function(require,module,exports){arguments[4][73][0].apply(exports,arguments)},{dup:73}],203:[function(require,module,exports){"use strict";function _inheritsLoose(subClass,superClass){subClass.prototype=Object.create(superClass.prototype);subClass.prototype.constructor=subClass;subClass.__proto__=superClass}var codes={};function createErrorType(code,message,Base){if(!Base){Base=Error}function getMessage(arg1,arg2,arg3){if(typeof message==="string"){return message}else{return message(arg1,arg2,arg3)}}var NodeError=function(_Base){_inheritsLoose(NodeError,_Base);function NodeError(arg1,arg2,arg3){return _Base.call(this,getMessage(arg1,arg2,arg3))||this}return NodeError}(Base);NodeError.prototype.name=Base.name;NodeError.prototype.code=code;codes[code]=NodeError}function oneOf(expected,thing){if(Array.isArray(expected)){var len=expected.length;expected=expected.map((function(i){return String(i)}));if(len>2){return"one of ".concat(thing," ").concat(expected.slice(0,len-1).join(", "),", or ")+expected[len-1]}else if(len===2){return"one of ".concat(thing," ").concat(expected[0]," or ").concat(expected[1])}else{return"of ".concat(thing," ").concat(expected[0])}}else{return"of ".concat(thing," ").concat(String(expected))}}function startsWith(str,search,pos){return str.substr(!pos||pos<0?0:+pos,search.length)===search}function endsWith(str,search,this_len){if(this_len===undefined||this_len>str.length){this_len=str.length}return str.substring(this_len-search.length,this_len)===search}function includes(str,search,start){if(typeof start!=="number"){start=0}if(start+search.length>str.length){return false}else{return str.indexOf(search,start)!==-1}}createErrorType("ERR_INVALID_OPT_VALUE",(function(name,value){return'The value "'+value+'" is invalid for option "'+name+'"'}),TypeError);createErrorType("ERR_INVALID_ARG_TYPE",(function(name,expected,actual){var determiner;if(typeof expected==="string"&&startsWith(expected,"not ")){determiner="must not be";expected=expected.replace(/^not /,"")}else{determiner="must be"}var msg;if(endsWith(name," argument")){msg="The ".concat(name," ").concat(determiner," ").concat(oneOf(expected,"type"))}else{var type=includes(name,".")?"property":"argument";msg='The "'.concat(name,'" ').concat(type," ").concat(determiner," ").concat(oneOf(expected,"type"))}msg+=". Received type ".concat(typeof actual);return msg}),TypeError);createErrorType("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");createErrorType("ERR_METHOD_NOT_IMPLEMENTED",(function(name){return"The "+name+" method is not implemented"}));createErrorType("ERR_STREAM_PREMATURE_CLOSE","Premature close");createErrorType("ERR_STREAM_DESTROYED",(function(name){return"Cannot call "+name+" after a stream was destroyed"}));createErrorType("ERR_MULTIPLE_CALLBACK","Callback called multiple times");createErrorType("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end");createErrorType("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);createErrorType("ERR_UNKNOWN_ENCODING",(function(arg){return"Unknown encoding: "+arg}),TypeError);createErrorType("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");module.exports.codes=codes},{}],204:[function(require,module,exports){(function(process){(function(){"use strict";var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");require("inherits")(Duplex,Readable);{var keys=objectKeys(Writable.prototype);for(var v=0;v0){if(typeof chunk!=="string"&&!state.objectMode&&Object.getPrototypeOf(chunk)!==Buffer.prototype){chunk=_uint8ArrayToBuffer(chunk)}if(addToFront){if(state.endEmitted)errorOrDestroy(stream,new ERR_STREAM_UNSHIFT_AFTER_END_EVENT);else addChunk(stream,state,chunk,true)}else if(state.ended){errorOrDestroy(stream,new ERR_STREAM_PUSH_AFTER_EOF)}else if(state.destroyed){return false}else{state.reading=false;if(state.decoder&&!encoding){chunk=state.decoder.write(chunk);if(state.objectMode||chunk.length!==0)addChunk(stream,state,chunk,false);else maybeReadMore(stream,state)}else{addChunk(stream,state,chunk,false)}}}else if(!addToFront){state.reading=false;maybeReadMore(stream,state)}}return!state.ended&&(state.length=MAX_HWM){n=MAX_HWM}else{n--;n|=n>>>1;n|=n>>>2;n|=n>>>4;n|=n>>>8;n|=n>>>16;n++}return n}function howMuchToRead(n,state){if(n<=0||state.length===0&&state.ended)return 0;if(state.objectMode)return 1;if(n!==n){if(state.flowing&&state.length)return state.buffer.head.data.length;else return state.length}if(n>state.highWaterMark)state.highWaterMark=computeNewHighWaterMark(n);if(n<=state.length)return n;if(!state.ended){state.needReadable=true;return 0}return state.length}Readable.prototype.read=function(n){debug("read",n);n=parseInt(n,10);var state=this._readableState;var nOrig=n;if(n!==0)state.emittedReadable=false;if(n===0&&state.needReadable&&((state.highWaterMark!==0?state.length>=state.highWaterMark:state.length>0)||state.ended)){debug("read: emitReadable",state.length,state.ended);if(state.length===0&&state.ended)endReadable(this);else emitReadable(this);return null}n=howMuchToRead(n,state);if(n===0&&state.ended){if(state.length===0)endReadable(this);return null}var doRead=state.needReadable;debug("need readable",doRead);if(state.length===0||state.length-n0)ret=fromList(n,state);else ret=null;if(ret===null){state.needReadable=state.length<=state.highWaterMark;n=0}else{state.length-=n;state.awaitDrain=0}if(state.length===0){if(!state.ended)state.needReadable=true;if(nOrig!==n&&state.ended)endReadable(this)}if(ret!==null)this.emit("data",ret);return ret};function onEofChunk(stream,state){debug("onEofChunk");if(state.ended)return;if(state.decoder){var chunk=state.decoder.end();if(chunk&&chunk.length){state.buffer.push(chunk);state.length+=state.objectMode?1:chunk.length}}state.ended=true;if(state.sync){emitReadable(stream)}else{state.needReadable=false;if(!state.emittedReadable){state.emittedReadable=true;emitReadable_(stream)}}}function emitReadable(stream){var state=stream._readableState;debug("emitReadable",state.needReadable,state.emittedReadable);state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;process.nextTick(emitReadable_,stream)}}function emitReadable_(stream){var state=stream._readableState;debug("emitReadable_",state.destroyed,state.length,state.ended);if(!state.destroyed&&(state.length||state.ended)){stream.emit("readable");state.emittedReadable=false}state.needReadable=!state.flowing&&!state.ended&&state.length<=state.highWaterMark;flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;process.nextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){while(!state.reading&&!state.ended&&(state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",state.awaitDrain);state.awaitDrain++}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)errorOrDestroy(dest,er)}prependListener(dest,"error",onerror);function onclose(){dest.removeListener("finish",onfinish);unpipe()}dest.once("close",onclose);function onfinish(){debug("onfinish");dest.removeListener("close",onclose);unpipe()}dest.once("finish",onfinish);function unpipe(){debug("unpipe");src.unpipe(dest)}dest.emit("pipe",src);if(!state.flowing){debug("pipe resume");src.resume()}return dest};function pipeOnDrain(src){return function pipeOnDrainFunctionResult(){var state=src._readableState;debug("pipeOnDrain",state.awaitDrain);if(state.awaitDrain)state.awaitDrain--;if(state.awaitDrain===0&&EElistenerCount(src,"data")){state.flowing=true;flow(src)}}}Readable.prototype.unpipe=function(dest){var state=this._readableState;var unpipeInfo={hasUnpiped:false};if(state.pipesCount===0)return this;if(state.pipesCount===1){if(dest&&dest!==state.pipes)return this;if(!dest)dest=state.pipes;state.pipes=null;state.pipesCount=0;state.flowing=false;if(dest)dest.emit("unpipe",this,unpipeInfo);return this}if(!dest){var dests=state.pipes;var len=state.pipesCount;state.pipes=null;state.pipesCount=0;state.flowing=false;for(var i=0;i0;if(state.flowing!==false)this.resume()}else if(ev==="readable"){if(!state.endEmitted&&!state.readableListening){state.readableListening=state.needReadable=true;state.flowing=false;state.emittedReadable=false;debug("on readable",state.length,state.reading);if(state.length){emitReadable(this)}else if(!state.reading){process.nextTick(nReadingNextTick,this)}}}return res};Readable.prototype.addListener=Readable.prototype.on;Readable.prototype.removeListener=function(ev,fn){var res=Stream.prototype.removeListener.call(this,ev,fn);if(ev==="readable"){process.nextTick(updateReadableListening,this)}return res};Readable.prototype.removeAllListeners=function(ev){var res=Stream.prototype.removeAllListeners.apply(this,arguments);if(ev==="readable"||ev===undefined){process.nextTick(updateReadableListening,this)}return res};function updateReadableListening(self){var state=self._readableState;state.readableListening=self.listenerCount("readable")>0;if(state.resumeScheduled&&!state.paused){state.flowing=true}else if(self.listenerCount("data")>0){self.resume()}}function nReadingNextTick(self){debug("readable nexttick read 0");self.read(0)}Readable.prototype.resume=function(){var state=this._readableState;if(!state.flowing){debug("resume");state.flowing=!state.readableListening;resume(this,state)}state.paused=false;return this};function resume(stream,state){if(!state.resumeScheduled){state.resumeScheduled=true;process.nextTick(resume_,stream,state)}}function resume_(stream,state){debug("resume",state.reading);if(!state.reading){stream.read(0)}state.resumeScheduled=false;stream.emit("resume");flow(stream);if(state.flowing&&!state.reading)stream.read(0)}Readable.prototype.pause=function(){debug("call pause flowing=%j",this._readableState.flowing);if(this._readableState.flowing!==false){debug("pause");this._readableState.flowing=false;this.emit("pause")}this._readableState.paused=true;return this};function flow(stream){var state=stream._readableState;debug("flow",state.flowing);while(state.flowing&&stream.read()!==null){}}Readable.prototype.wrap=function(stream){var _this=this;var state=this._readableState;var paused=false;stream.on("end",(function(){debug("wrapped end");if(state.decoder&&!state.ended){var chunk=state.decoder.end();if(chunk&&chunk.length)_this.push(chunk)}_this.push(null)}));stream.on("data",(function(chunk){debug("wrapped data");if(state.decoder)chunk=state.decoder.write(chunk);if(state.objectMode&&(chunk===null||chunk===undefined))return;else if(!state.objectMode&&(!chunk||!chunk.length))return;var ret=_this.push(chunk);if(!ret){paused=true;stream.pause()}}));for(var i in stream){if(this[i]===undefined&&typeof stream[i]==="function"){this[i]=function methodWrap(method){return function methodWrapReturnFunction(){return stream[method].apply(stream,arguments)}}(i)}}for(var n=0;n=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.first();else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=state.buffer.consume(n,state.decoder)}return ret}function endReadable(stream){var state=stream._readableState;debug("endReadable",state.endEmitted);if(!state.endEmitted){state.ended=true;process.nextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){debug("endReadableNT",state.endEmitted,state.length);if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end");if(state.autoDestroy){var wState=stream._writableState;if(!wState||wState.autoDestroy&&wState.finished){stream.destroy()}}}}if(typeof Symbol==="function"){Readable.from=function(iterable,opts){if(from===undefined){from=require("./internal/streams/from")}return from(Readable,iterable,opts)}}function indexOf(xs,x){for(var i=0,l=xs.length;i-1))throw new ERR_UNKNOWN_ENCODING(encoding);this._writableState.defaultEncoding=encoding;return this};Object.defineProperty(Writable.prototype,"writableBuffer",{enumerable:false,get:function get(){return this._writableState&&this._writableState.getBuffer()}});function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=Buffer.from(chunk,encoding)}return chunk}Object.defineProperty(Writable.prototype,"writableHighWaterMark",{enumerable:false,get:function get(){return this._writableState.highWaterMark}});function writeOrBuffer(stream,state,isBuf,chunk,encoding,cb){if(!isBuf){var newChunk=decodeChunk(state,chunk,encoding);if(chunk!==newChunk){isBuf=true;encoding="buffer";chunk=newChunk}}var len=state.objectMode?1:chunk.length;state.length+=len;var ret=state.length0)this.tail.next=entry;else this.head=entry;this.tail=entry;++this.length}},{key:"unshift",value:function unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length}},{key:"shift",value:function shift(){if(this.length===0)return;var ret=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;--this.length;return ret}},{key:"clear",value:function clear(){this.head=this.tail=null;this.length=0}},{key:"join",value:function join(s){if(this.length===0)return"";var p=this.head;var ret=""+p.data;while(p=p.next){ret+=s+p.data}return ret}},{key:"concat",value:function concat(n){if(this.length===0)return Buffer.alloc(0);var ret=Buffer.allocUnsafe(n>>>0);var p=this.head;var i=0;while(p){copyBuffer(p.data,ret,i);i+=p.data.length;p=p.next}return ret}},{key:"consume",value:function consume(n,hasStrings){var ret;if(nstr.length?str.length:n;if(nb===str.length)ret+=str;else ret+=str.slice(0,n);n-=nb;if(n===0){if(nb===str.length){++c;if(p.next)this.head=p.next;else this.head=this.tail=null}else{this.head=p;p.data=str.slice(nb)}break}++c}this.length-=c;return ret}},{key:"_getBuffer",value:function _getBuffer(n){var ret=Buffer.allocUnsafe(n);var p=this.head;var c=1;p.data.copy(ret);n-=p.data.length;while(p=p.next){var buf=p.data;var nb=n>buf.length?buf.length:n;buf.copy(ret,ret.length-n,0,nb);n-=nb;if(n===0){if(nb===buf.length){++c;if(p.next)this.head=p.next;else this.head=this.tail=null}else{this.head=p;p.data=buf.slice(nb)}break}++c}this.length-=c;return ret}},{key:custom,value:function value(_,options){return inspect(this,_objectSpread({},options,{depth:0,customInspect:false}))}}]);return BufferList}()},{buffer:32,util:30}],211:[function(require,module,exports){(function(process){(function(){"use strict";function destroy(err,cb){var _this=this;var readableDestroyed=this._readableState&&this._readableState.destroyed;var writableDestroyed=this._writableState&&this._writableState.destroyed;if(readableDestroyed||writableDestroyed){if(cb){cb(err)}else if(err){if(!this._writableState){process.nextTick(emitErrorNT,this,err)}else if(!this._writableState.errorEmitted){this._writableState.errorEmitted=true;process.nextTick(emitErrorNT,this,err)}}return this}if(this._readableState){this._readableState.destroyed=true}if(this._writableState){this._writableState.destroyed=true}this._destroy(err||null,(function(err){if(!cb&&err){if(!_this._writableState){process.nextTick(emitErrorAndCloseNT,_this,err)}else if(!_this._writableState.errorEmitted){_this._writableState.errorEmitted=true;process.nextTick(emitErrorAndCloseNT,_this,err)}else{process.nextTick(emitCloseNT,_this)}}else if(cb){process.nextTick(emitCloseNT,_this);cb(err)}else{process.nextTick(emitCloseNT,_this)}}));return this}function emitErrorAndCloseNT(self,err){emitErrorNT(self,err);emitCloseNT(self)}function emitCloseNT(self){if(self._writableState&&!self._writableState.emitClose)return;if(self._readableState&&!self._readableState.emitClose)return;self.emit("close")}function undestroy(){if(this._readableState){this._readableState.destroyed=false;this._readableState.reading=false;this._readableState.ended=false;this._readableState.endEmitted=false}if(this._writableState){this._writableState.destroyed=false;this._writableState.ended=false;this._writableState.ending=false;this._writableState.finalCalled=false;this._writableState.prefinished=false;this._writableState.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}function errorOrDestroy(stream,err){var rState=stream._readableState;var wState=stream._writableState;if(rState&&rState.autoDestroy||wState&&wState.autoDestroy)stream.destroy(err);else stream.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy,errorOrDestroy:errorOrDestroy}}).call(this)}).call(this,require("_process"))},{_process:174}],212:[function(require,module,exports){"use strict";var ERR_STREAM_PREMATURE_CLOSE=require("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;function once(callback){var called=false;return function(){if(called)return;called=true;for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key]}callback.apply(this,args)}}function noop(){}function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"}function eos(stream,opts,callback){if(typeof opts==="function")return eos(stream,null,opts);if(!opts)opts={};callback=once(callback||noop);var readable=opts.readable||opts.readable!==false&&stream.readable;var writable=opts.writable||opts.writable!==false&&stream.writable;var onlegacyfinish=function onlegacyfinish(){if(!stream.writable)onfinish()};var writableEnded=stream._writableState&&stream._writableState.finished;var onfinish=function onfinish(){writable=false;writableEnded=true;if(!readable)callback.call(stream)};var readableEnded=stream._readableState&&stream._readableState.endEmitted;var onend=function onend(){readable=false;readableEnded=true;if(!writable)callback.call(stream)};var onerror=function onerror(err){callback.call(stream,err)};var onclose=function onclose(){var err;if(readable&&!readableEnded){if(!stream._readableState||!stream._readableState.ended)err=new ERR_STREAM_PREMATURE_CLOSE;return callback.call(stream,err)}if(writable&&!writableEnded){if(!stream._writableState||!stream._writableState.ended)err=new ERR_STREAM_PREMATURE_CLOSE;return callback.call(stream,err)}};var onrequest=function onrequest(){stream.req.on("finish",onfinish)};if(isRequest(stream)){stream.on("complete",onfinish);stream.on("abort",onclose);if(stream.req)onrequest();else stream.on("request",onrequest)}else if(writable&&!stream._writableState){stream.on("end",onlegacyfinish);stream.on("close",onlegacyfinish)}stream.on("end",onend);stream.on("finish",onfinish);if(opts.error!==false)stream.on("error",onerror);stream.on("close",onclose);return function(){stream.removeListener("complete",onfinish);stream.removeListener("abort",onclose);stream.removeListener("request",onrequest);if(stream.req)stream.req.removeListener("finish",onfinish);stream.removeListener("end",onlegacyfinish);stream.removeListener("close",onlegacyfinish);stream.removeListener("finish",onfinish);stream.removeListener("end",onend);stream.removeListener("error",onerror);stream.removeListener("close",onclose)}}module.exports=eos},{"../../../errors":203}],213:[function(require,module,exports){module.exports=function(){throw new Error("Readable.from is not available in the browser")}},{}],214:[function(require,module,exports){"use strict";var eos;function once(callback){var called=false;return function(){if(called)return;called=true;callback.apply(void 0,arguments)}}var _require$codes=require("../../../errors").codes,ERR_MISSING_ARGS=_require$codes.ERR_MISSING_ARGS,ERR_STREAM_DESTROYED=_require$codes.ERR_STREAM_DESTROYED;function noop(err){if(err)throw err}function isRequest(stream){return stream.setHeader&&typeof stream.abort==="function"}function destroyer(stream,reading,writing,callback){callback=once(callback);var closed=false;stream.on("close",(function(){closed=true}));if(eos===undefined)eos=require("./end-of-stream");eos(stream,{readable:reading,writable:writing},(function(err){if(err)return callback(err);closed=true;callback()}));var destroyed=false;return function(err){if(closed)return;if(destroyed)return;destroyed=true;if(isRequest(stream))return stream.abort();if(typeof stream.destroy==="function")return stream.destroy();callback(err||new ERR_STREAM_DESTROYED("pipe"))}}function call(fn){fn()}function pipe(from,to){return from.pipe(to)}function popCallback(streams){if(!streams.length)return noop;if(typeof streams[streams.length-1]!=="function")return noop;return streams.pop()}function pipeline(){for(var _len=arguments.length,streams=new Array(_len),_key=0;_key<_len;_key++){streams[_key]=arguments[_key]}var callback=popCallback(streams);if(Array.isArray(streams[0]))streams=streams[0];if(streams.length<2){throw new ERR_MISSING_ARGS("streams")}var error;var destroys=streams.map((function(stream,i){var reading=i0;return destroyer(stream,reading,writing,(function(err){if(!error)error=err;if(err)destroys.forEach(call);if(reading)return;destroys.forEach(call);callback(error)}))}));return streams.reduce(pipe)}module.exports=pipeline},{"../../../errors":203,"./end-of-stream":212}],215:[function(require,module,exports){"use strict";var ERR_INVALID_OPT_VALUE=require("../../../errors").codes.ERR_INVALID_OPT_VALUE;function highWaterMarkFrom(options,isDuplex,duplexKey){return options.highWaterMark!=null?options.highWaterMark:isDuplex?options[duplexKey]:null}function getHighWaterMark(state,options,duplexKey,isDuplex){var hwm=highWaterMarkFrom(options,isDuplex,duplexKey);if(hwm!=null){if(!(isFinite(hwm)&&Math.floor(hwm)===hwm)||hwm<0){var name=isDuplex?duplexKey:"highWaterMark";throw new ERR_INVALID_OPT_VALUE(name,hwm)}return Math.floor(hwm)}return state.objectMode?16:16*1024}module.exports={getHighWaterMark:getHighWaterMark}},{"../../../errors":203}],216:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:31}],217:[function(require,module,exports){exports=module.exports=require("./lib/_stream_readable.js");exports.Stream=exports;exports.Readable=exports;exports.Writable=require("./lib/_stream_writable.js");exports.Duplex=require("./lib/_stream_duplex.js");exports.Transform=require("./lib/_stream_transform.js");exports.PassThrough=require("./lib/_stream_passthrough.js");exports.finished=require("./lib/internal/streams/end-of-stream.js");exports.pipeline=require("./lib/internal/streams/pipeline.js")},{"./lib/_stream_duplex.js":204,"./lib/_stream_passthrough.js":205,"./lib/_stream_readable.js":206,"./lib/_stream_transform.js":207,"./lib/_stream_writable.js":208,"./lib/internal/streams/end-of-stream.js":212,"./lib/internal/streams/pipeline.js":214}],218:[function(require,module,exports){"use strict";var Buffer=require("safe-buffer").Buffer;var isEncoding=Buffer.isEncoding||function(encoding){encoding=""+encoding;switch(encoding&&encoding.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return true;default:return false}};function _normalizeEncoding(enc){if(!enc)return"utf8";var retried;while(true){switch(enc){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return enc;default:if(retried)return;enc=(""+enc).toLowerCase();retried=true}}}function normalizeEncoding(enc){var nenc=_normalizeEncoding(enc);if(typeof nenc!=="string"&&(Buffer.isEncoding===isEncoding||!isEncoding(enc)))throw new Error("Unknown encoding: "+enc);return nenc||enc}exports.StringDecoder=StringDecoder;function StringDecoder(encoding){this.encoding=normalizeEncoding(encoding);var nb;switch(this.encoding){case"utf16le":this.text=utf16Text;this.end=utf16End;nb=4;break;case"utf8":this.fillLast=utf8FillLast;nb=4;break;case"base64":this.text=base64Text;this.end=base64End;nb=3;break;default:this.write=simpleWrite;this.end=simpleEnd;return}this.lastNeed=0;this.lastTotal=0;this.lastChar=Buffer.allocUnsafe(nb)}StringDecoder.prototype.write=function(buf){if(buf.length===0)return"";var r;var i;if(this.lastNeed){r=this.fillLast(buf);if(r===undefined)return"";i=this.lastNeed;this.lastNeed=0}else{i=0}if(i>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return byte>>6===2?-1:-2}function utf8CheckIncomplete(self,buf,i){var j=buf.length-1;if(j=0){if(nb>0)self.lastNeed=nb-1;return nb}if(--j=0){if(nb>0)self.lastNeed=nb-2;return nb}if(--j=0){if(nb>0){if(nb===2)nb=0;else self.lastNeed=nb-3}return nb}return 0}function utf8CheckExtraBytes(self,buf,p){if((buf[0]&192)!==128){self.lastNeed=0;return"�"}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�"}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�"}}}}function utf8FillLast(buf){var p=this.lastTotal-this.lastNeed;var r=utf8CheckExtraBytes(this,buf,p);if(r!==undefined)return r;if(this.lastNeed<=buf.length){buf.copy(this.lastChar,p,0,this.lastNeed);return this.lastChar.toString(this.encoding,0,this.lastTotal)}buf.copy(this.lastChar,p,0,buf.length);this.lastNeed-=buf.length}function utf8Text(buf,i){var total=utf8CheckIncomplete(this,buf,i);if(!this.lastNeed)return buf.toString("utf8",i);this.lastTotal=total;var end=buf.length-(total-this.lastNeed);buf.copy(this.lastChar,0,end);return buf.toString("utf8",i,end)}function utf8End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+"�";return r}function utf16Text(buf,i){if((buf.length-i)%2===0){var r=buf.toString("utf16le",i);if(r){var c=r.charCodeAt(r.length-1);if(c>=55296&&c<=56319){this.lastNeed=2;this.lastTotal=4;this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1];return r.slice(0,-1)}}return r}this.lastNeed=1;this.lastTotal=2;this.lastChar[0]=buf[buf.length-1];return buf.toString("utf16le",i,buf.length-1)}function utf16End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed){var end=this.lastTotal-this.lastNeed;return r+this.lastChar.toString("utf16le",0,end)}return r}function base64Text(buf,i){var n=(buf.length-i)%3;if(n===0)return buf.toString("base64",i);this.lastNeed=3-n;this.lastTotal=3;if(n===1){this.lastChar[0]=buf[buf.length-1]}else{this.lastChar[0]=buf[buf.length-2];this.lastChar[1]=buf[buf.length-1]}return buf.toString("base64",i,buf.length-n)}function base64End(buf){var r=buf&&buf.length?this.write(buf):"";if(this.lastNeed)return r+this.lastChar.toString("base64",0,3-this.lastNeed);return r}function simpleWrite(buf){return buf.toString(this.encoding)}function simpleEnd(buf){return buf&&buf.length?this.write(buf):""}},{"safe-buffer":187}],219:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.default=exports.connect=exports.io=exports.Socket=exports.Manager=exports.protocol=void 0;const url_js_1=require("./url.js");const manager_js_1=require("./manager.js");Object.defineProperty(exports,"Manager",{enumerable:true,get:function(){return manager_js_1.Manager}});const socket_js_1=require("./socket.js");Object.defineProperty(exports,"Socket",{enumerable:true,get:function(){return socket_js_1.Socket}});const debug_1=__importDefault(require("debug"));const debug=debug_1.default("socket.io-client");const cache={};function lookup(uri,opts){if(typeof uri==="object"){opts=uri;uri=undefined}opts=opts||{};const parsed=url_js_1.url(uri,opts.path||"/socket.io");const source=parsed.source;const id=parsed.id;const path=parsed.path;const sameNamespace=cache[id]&&path in cache[id]["nsps"];const newConnection=opts.forceNew||opts["force new connection"]||false===opts.multiplex||sameNamespace;let io;if(newConnection){debug("ignoring socket cache for %s",source);io=new manager_js_1.Manager(source,opts)}else{if(!cache[id]){debug("new io instance for %s",source);cache[id]=new manager_js_1.Manager(source,opts)}io=cache[id]}if(parsed.query&&!opts.query){opts.query=parsed.queryKey}return io.socket(parsed.path,opts)}exports.io=lookup;exports.connect=lookup;exports.default=lookup;Object.assign(lookup,{Manager:manager_js_1.Manager,Socket:socket_js_1.Socket,io:lookup,connect:lookup});var socket_io_parser_1=require("socket.io-parser");Object.defineProperty(exports,"protocol",{enumerable:true,get:function(){return socket_io_parser_1.protocol}});module.exports=lookup},{"./manager.js":220,"./socket.js":222,"./url.js":223,debug:224,"socket.io-parser":228}],220:[function(require,module,exports){"use strict";var __createBinding=this&&this.__createBinding||(Object.create?function(o,m,k,k2){if(k2===undefined)k2=k;Object.defineProperty(o,k2,{enumerable:true,get:function(){return m[k]}})}:function(o,m,k,k2){if(k2===undefined)k2=k;o[k2]=m[k]});var __setModuleDefault=this&&this.__setModuleDefault||(Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}:function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k in mod)if(k!=="default"&&Object.prototype.hasOwnProperty.call(mod,k))__createBinding(result,mod,k);__setModuleDefault(result,mod);return result};var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.Manager=void 0;const engine_io_client_1=require("engine.io-client");const socket_js_1=require("./socket.js");const parser=__importStar(require("socket.io-parser"));const on_js_1=require("./on.js");const backo2_1=__importDefault(require("backo2"));const component_emitter_1=require("@socket.io/component-emitter");const debug_1=__importDefault(require("debug"));const debug=debug_1.default("socket.io-client:manager");class Manager extends component_emitter_1.Emitter{constructor(uri,opts){var _a;super();this.nsps={};this.subs=[];if(uri&&"object"===typeof uri){opts=uri;uri=undefined}opts=opts||{};opts.path=opts.path||"/socket.io";this.opts=opts;engine_io_client_1.installTimerFunctions(this,opts);this.reconnection(opts.reconnection!==false);this.reconnectionAttempts(opts.reconnectionAttempts||Infinity);this.reconnectionDelay(opts.reconnectionDelay||1e3);this.reconnectionDelayMax(opts.reconnectionDelayMax||5e3);this.randomizationFactor((_a=opts.randomizationFactor)!==null&&_a!==void 0?_a:.5);this.backoff=new backo2_1.default({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()});this.timeout(null==opts.timeout?2e4:opts.timeout);this._readyState="closed";this.uri=uri;const _parser=opts.parser||parser;this.encoder=new _parser.Encoder;this.decoder=new _parser.Decoder;this._autoConnect=opts.autoConnect!==false;if(this._autoConnect)this.open()}reconnection(v){if(!arguments.length)return this._reconnection;this._reconnection=!!v;return this}reconnectionAttempts(v){if(v===undefined)return this._reconnectionAttempts;this._reconnectionAttempts=v;return this}reconnectionDelay(v){var _a;if(v===undefined)return this._reconnectionDelay;this._reconnectionDelay=v;(_a=this.backoff)===null||_a===void 0?void 0:_a.setMin(v);return this}randomizationFactor(v){var _a;if(v===undefined)return this._randomizationFactor;this._randomizationFactor=v;(_a=this.backoff)===null||_a===void 0?void 0:_a.setJitter(v);return this}reconnectionDelayMax(v){var _a;if(v===undefined)return this._reconnectionDelayMax;this._reconnectionDelayMax=v;(_a=this.backoff)===null||_a===void 0?void 0:_a.setMax(v);return this}timeout(v){if(!arguments.length)return this._timeout;this._timeout=v;return this}maybeReconnectOnOpen(){if(!this._reconnecting&&this._reconnection&&this.backoff.attempts===0){this.reconnect()}}open(fn){debug("readyState %s",this._readyState);if(~this._readyState.indexOf("open"))return this;debug("opening %s",this.uri);this.engine=new engine_io_client_1.Socket(this.uri,this.opts);const socket=this.engine;const self=this;this._readyState="opening";this.skipReconnect=false;const openSubDestroy=on_js_1.on(socket,"open",(function(){self.onopen();fn&&fn()}));const errorSub=on_js_1.on(socket,"error",(err=>{debug("error");self.cleanup();self._readyState="closed";this.emitReserved("error",err);if(fn){fn(err)}else{self.maybeReconnectOnOpen()}}));if(false!==this._timeout){const timeout=this._timeout;debug("connect attempt will timeout after %d",timeout);if(timeout===0){openSubDestroy()}const timer=this.setTimeoutFn((()=>{debug("connect attempt timed out after %d",timeout);openSubDestroy();socket.close();socket.emit("error",new Error("timeout"))}),timeout);if(this.opts.autoUnref){timer.unref()}this.subs.push((function subDestroy(){clearTimeout(timer)}))}this.subs.push(openSubDestroy);this.subs.push(errorSub);return this}connect(fn){return this.open(fn)}onopen(){debug("open");this.cleanup();this._readyState="open";this.emitReserved("open");const socket=this.engine;this.subs.push(on_js_1.on(socket,"ping",this.onping.bind(this)),on_js_1.on(socket,"data",this.ondata.bind(this)),on_js_1.on(socket,"error",this.onerror.bind(this)),on_js_1.on(socket,"close",this.onclose.bind(this)),on_js_1.on(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(data){this.decoder.add(data)}ondecoded(packet){this.emitReserved("packet",packet)}onerror(err){debug("error",err);this.emitReserved("error",err)}socket(nsp,opts){let socket=this.nsps[nsp];if(!socket){socket=new socket_js_1.Socket(this,nsp,opts);this.nsps[nsp]=socket}return socket}_destroy(socket){const nsps=Object.keys(this.nsps);for(const nsp of nsps){const socket=this.nsps[nsp];if(socket.active){debug("socket %s is still active, skipping close",nsp);return}}this._close()}_packet(packet){debug("writing packet %j",packet);const encodedPackets=this.encoder.encode(packet);for(let i=0;isubDestroy()));this.subs.length=0;this.decoder.destroy()}_close(){debug("disconnect");this.skipReconnect=true;this._reconnecting=false;this.onclose("forced close");if(this.engine)this.engine.close()}disconnect(){return this._close()}onclose(reason){debug("closed due to %s",reason);this.cleanup();this.backoff.reset();this._readyState="closed";this.emitReserved("close",reason);if(this._reconnection&&!this.skipReconnect){this.reconnect()}}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const self=this;if(this.backoff.attempts>=this._reconnectionAttempts){debug("reconnect failed");this.backoff.reset();this.emitReserved("reconnect_failed");this._reconnecting=false}else{const delay=this.backoff.duration();debug("will wait %dms before reconnect attempt",delay);this._reconnecting=true;const timer=this.setTimeoutFn((()=>{if(self.skipReconnect)return;debug("attempting reconnect");this.emitReserved("reconnect_attempt",self.backoff.attempts);if(self.skipReconnect)return;self.open((err=>{if(err){debug("reconnect attempt error");self._reconnecting=false;self.reconnect();this.emitReserved("reconnect_error",err)}else{debug("reconnect success");self.onreconnect()}}))}),delay);if(this.opts.autoUnref){timer.unref()}this.subs.push((function subDestroy(){clearTimeout(timer)}))}}onreconnect(){const attempt=this.backoff.attempts;this._reconnecting=false;this.backoff.reset();this.emitReserved("reconnect",attempt)}}exports.Manager=Manager},{"./on.js":221,"./socket.js":222,"@socket.io/component-emitter":17,backo2:27,debug:224,"engine.io-client":61,"socket.io-parser":228}],221:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.on=void 0;function on(obj,ev,fn){obj.on(ev,fn);return function subDestroy(){obj.off(ev,fn)}}exports.on=on},{}],222:[function(require,module,exports){"use strict";var __importDefault=this&&this.__importDefault||function(mod){return mod&&mod.__esModule?mod:{default:mod}};Object.defineProperty(exports,"__esModule",{value:true});exports.Socket=void 0;const socket_io_parser_1=require("socket.io-parser");const on_js_1=require("./on.js");const component_emitter_1=require("@socket.io/component-emitter");const debug_1=__importDefault(require("debug"));const debug=debug_1.default("socket.io-client:socket");const RESERVED_EVENTS=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class Socket extends component_emitter_1.Emitter{constructor(io,nsp,opts){super();this.connected=false;this.disconnected=true;this.receiveBuffer=[];this.sendBuffer=[];this.ids=0;this.acks={};this.flags={};this.io=io;this.nsp=nsp;if(opts&&opts.auth){this.auth=opts.auth}if(this.io._autoConnect)this.open()}subEvents(){if(this.subs)return;const io=this.io;this.subs=[on_js_1.on(io,"open",this.onopen.bind(this)),on_js_1.on(io,"packet",this.onpacket.bind(this)),on_js_1.on(io,"error",this.onerror.bind(this)),on_js_1.on(io,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){if(this.connected)return this;this.subEvents();if(!this.io["_reconnecting"])this.io.open();if("open"===this.io._readyState)this.onopen();return this}open(){return this.connect()}send(...args){args.unshift("message");this.emit.apply(this,args);return this}emit(ev,...args){if(RESERVED_EVENTS.hasOwnProperty(ev)){throw new Error('"'+ev+'" is a reserved event name')}args.unshift(ev);const packet={type:socket_io_parser_1.PacketType.EVENT,data:args};packet.options={};packet.options.compress=this.flags.compress!==false;if("function"===typeof args[args.length-1]){const id=this.ids++;debug("emitting packet with ack id %d",id);const ack=args.pop();this._registerAckCallback(id,ack);packet.id=id}const isTransportWritable=this.io.engine&&this.io.engine.transport&&this.io.engine.transport.writable;const discardPacket=this.flags.volatile&&(!isTransportWritable||!this.connected);if(discardPacket){debug("discard packet as the transport is not currently writable")}else if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}this.flags={};return this}_registerAckCallback(id,ack){const timeout=this.flags.timeout;if(timeout===undefined){this.acks[id]=ack;return}const timer=this.io.setTimeoutFn((()=>{delete this.acks[id];for(let i=0;i{this.io.clearTimeoutFn(timer);ack.apply(this,[null,...args])}}packet(packet){packet.nsp=this.nsp;this.io._packet(packet)}onopen(){debug("transport is open - connecting");if(typeof this.auth=="function"){this.auth((data=>{this.packet({type:socket_io_parser_1.PacketType.CONNECT,data:data})}))}else{this.packet({type:socket_io_parser_1.PacketType.CONNECT,data:this.auth})}}onerror(err){if(!this.connected){this.emitReserved("connect_error",err)}}onclose(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;delete this.id;this.emitReserved("disconnect",reason)}onpacket(packet){const sameNamespace=packet.nsp===this.nsp;if(!sameNamespace)return;switch(packet.type){case socket_io_parser_1.PacketType.CONNECT:if(packet.data&&packet.data.sid){const id=packet.data.sid;this.onconnect(id)}else{this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"))}break;case socket_io_parser_1.PacketType.EVENT:this.onevent(packet);break;case socket_io_parser_1.PacketType.BINARY_EVENT:this.onevent(packet);break;case socket_io_parser_1.PacketType.ACK:this.onack(packet);break;case socket_io_parser_1.PacketType.BINARY_ACK:this.onack(packet);break;case socket_io_parser_1.PacketType.DISCONNECT:this.ondisconnect();break;case socket_io_parser_1.PacketType.CONNECT_ERROR:this.destroy();const err=new Error(packet.data.message);err.data=packet.data.data;this.emitReserved("connect_error",err);break}}onevent(packet){const args=packet.data||[];debug("emitting event %j",args);if(null!=packet.id){debug("attaching ack callback to event");args.push(this.ack(packet.id))}if(this.connected){this.emitEvent(args)}else{this.receiveBuffer.push(Object.freeze(args))}}emitEvent(args){if(this._anyListeners&&this._anyListeners.length){const listeners=this._anyListeners.slice();for(const listener of listeners){listener.apply(this,args)}}super.emit.apply(this,args)}ack(id){const self=this;let sent=false;return function(...args){if(sent)return;sent=true;debug("sending ack %j",args);self.packet({type:socket_io_parser_1.PacketType.ACK,id:id,data:args})}}onack(packet){const ack=this.acks[packet.id];if("function"===typeof ack){debug("calling ack %s with %j",packet.id,packet.data);ack.apply(this,packet.data);delete this.acks[packet.id]}else{debug("bad ack %s",packet.id)}}onconnect(id){debug("socket connected with id %s",id);this.id=id;this.connected=true;this.disconnected=false;this.emitBuffered();this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach((args=>this.emitEvent(args)));this.receiveBuffer=[];this.sendBuffer.forEach((packet=>this.packet(packet)));this.sendBuffer=[]}ondisconnect(){debug("server disconnect (%s)",this.nsp);this.destroy();this.onclose("io server disconnect")}destroy(){if(this.subs){this.subs.forEach((subDestroy=>subDestroy()));this.subs=undefined}this.io["_destroy"](this)}disconnect(){if(this.connected){debug("performing disconnect (%s)",this.nsp);this.packet({type:socket_io_parser_1.PacketType.DISCONNECT})}this.destroy();if(this.connected){this.onclose("io client disconnect")}return this}close(){return this.disconnect()}compress(compress){this.flags.compress=compress;return this}get volatile(){this.flags.volatile=true;return this}timeout(timeout){this.flags.timeout=timeout;return this}onAny(listener){this._anyListeners=this._anyListeners||[];this._anyListeners.push(listener);return this}prependAny(listener){this._anyListeners=this._anyListeners||[];this._anyListeners.unshift(listener);return this}offAny(listener){if(!this._anyListeners){return this}if(listener){const listeners=this._anyListeners;for(let i=0;i{let warned=false;return()=>{if(!warned){warned=true;console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}}})();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){if(typeof window!=="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)){return true}if(typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)){return false}return typeof document!=="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!=="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function formatArgs(args){args[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+args[0]+(this.useColors?"%c ":" ")+"+"+module.exports.humanize(this.diff);if(!this.useColors){return}const c="color: "+this.color;args.splice(1,0,c,"color: inherit");let index=0;let lastC=0;args[0].replace(/%[a-zA-Z%]/g,(match=>{if(match==="%%"){return}index++;if(match==="%c"){lastC=index}}));args.splice(lastC,0,c)}exports.log=console.debug||console.log||(()=>{});function save(namespaces){try{if(namespaces){exports.storage.setItem("debug",namespaces)}else{exports.storage.removeItem("debug")}}catch(error){}}function load(){let r;try{r=exports.storage.getItem("debug")}catch(error){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}function localstorage(){try{return localStorage}catch(error){}}module.exports=require("./common")(exports);const{formatters:formatters}=module.exports;formatters.j=function(v){try{return JSON.stringify(v)}catch(error){return"[UnexpectedJSONParseError]: "+error.message}}}).call(this)}).call(this,require("_process"))},{"./common":225,_process:174}],225:[function(require,module,exports){arguments[4][72][0].apply(exports,arguments)},{dup:72,ms:226}],226:[function(require,module,exports){arguments[4][73][0].apply(exports,arguments)},{dup:73}],227:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.reconstructPacket=exports.deconstructPacket=void 0;const is_binary_js_1=require("./is-binary.js");function deconstructPacket(packet){const buffers=[];const packetData=packet.data;const pack=packet;pack.data=_deconstructPacket(packetData,buffers);pack.attachments=buffers.length;return{packet:pack,buffers:buffers}}exports.deconstructPacket=deconstructPacket;function _deconstructPacket(data,buffers){if(!data)return data;if(is_binary_js_1.isBinary(data)){const placeholder={_placeholder:true,num:buffers.length};buffers.push(data);return placeholder}else if(Array.isArray(data)){const newData=new Array(data.length);for(let i=0;i0;case PacketType.ACK:case PacketType.BINARY_ACK:return Array.isArray(payload)}}destroy(){if(this.reconstructor){this.reconstructor.finishedReconstruction()}}}exports.Decoder=Decoder;function tryParse(str){try{return JSON.parse(str)}catch(e){return false}}class BinaryReconstructor{constructor(packet){this.packet=packet;this.buffers=[];this.reconPack=packet}takeBinaryData(binData){this.buffers.push(binData);if(this.buffers.length===this.reconPack.attachments){const packet=binary_js_1.reconstructPacket(this.reconPack,this.buffers);this.finishedReconstruction();return packet}return null}finishedReconstruction(){this.reconPack=null;this.buffers=[]}}},{"./binary.js":227,"./is-binary.js":229,"@socket.io/component-emitter":17,debug:224}],229:[function(require,module,exports){"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.hasBinary=exports.isBinary=void 0;const withNativeArrayBuffer=typeof ArrayBuffer==="function";const isView=obj=>typeof ArrayBuffer.isView==="function"?ArrayBuffer.isView(obj):obj.buffer instanceof ArrayBuffer;const toString=Object.prototype.toString;const withNativeBlob=typeof Blob==="function"||typeof Blob!=="undefined"&&toString.call(Blob)==="[object BlobConstructor]";const withNativeFile=typeof File==="function"||typeof File!=="undefined"&&toString.call(File)==="[object FileConstructor]";function isBinary(obj){return withNativeArrayBuffer&&(obj instanceof ArrayBuffer||isView(obj))||withNativeBlob&&obj instanceof Blob||withNativeFile&&obj instanceof File}exports.isBinary=isBinary;function hasBinary(obj,toJSON){if(!obj||typeof obj!=="object"){return false}if(Array.isArray(obj)){for(let i=0,l=obj.length;i=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i0||string_ instanceof Object)?parse(string_):null};Response.prototype.toError=function(){var req=this.req;var method=req.method;var url=req.url;var message="cannot ".concat(method," ").concat(url," (").concat(this.status,")");var error=new Error(message);error.status=this.status;error.method=method;error.url=url;return error};request.Response=Response;function Request(method,url){var self=this;this._query=this._query||[];this.method=method;this.url=url;this.header={};this._header={};this.on("end",(function(){var error=null;var res=null;try{res=new Response(self)}catch(error_){error=new Error("Parser is unable to parse the response");error.parse=true;error.original=error_;if(self.xhr){error.rawResponse=typeof self.xhr.responseType==="undefined"?self.xhr.responseText:self.xhr.response;error.status=self.xhr.status?self.xhr.status:null;error.statusCode=error.status}else{error.rawResponse=null;error.status=null}return self.callback(error)}self.emit("response",res);var new_error;try{if(!self._isResponseOK(res)){new_error=new Error(res.statusText||res.text||"Unsuccessful HTTP response")}}catch(err){new_error=err}if(new_error){new_error.original=error;new_error.response=res;new_error.status=res.status;self.callback(new_error,res)}else{self.callback(null,res)}}))}Emitter(Request.prototype);RequestBase(Request.prototype);Request.prototype.type=function(type){this.set("Content-Type",request.types[type]||type);return this};Request.prototype.accept=function(type){this.set("Accept",request.types[type]||type);return this};Request.prototype.auth=function(user,pass,options){if(arguments.length===1)pass="";if(_typeof(pass)==="object"&&pass!==null){options=pass;pass=""}if(!options){options={type:typeof btoa==="function"?"basic":"auto"}}var encoder=function encoder(string){if(typeof btoa==="function"){return btoa(string)}throw new Error("Cannot use basic auth, btoa is not a function")};return this._auth(user,pass,options,encoder)};Request.prototype.query=function(value){if(typeof value!=="string")value=serialize(value);if(value)this._query.push(value);return this};Request.prototype.attach=function(field,file,options){if(file){if(this._data){throw new Error("superagent can't mix .send() and .attach()")}this._getFormData().append(field,file,options||file.name)}return this};Request.prototype._getFormData=function(){if(!this._formData){this._formData=new root.FormData}return this._formData};Request.prototype.callback=function(error,res){if(this._shouldRetry(error,res)){return this._retry()}var fn=this._callback;this.clearTimeout();if(error){if(this._maxRetries)error.retries=this._retries-1;this.emit("error",error)}fn(error,res)};Request.prototype.crossDomainError=function(){var error=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");error.crossDomain=true;error.status=this.status;error.method=this.method;error.url=this.url;this.callback(error)};Request.prototype.agent=function(){console.warn("This is not supported in browser version of superagent");return this};Request.prototype.ca=Request.prototype.agent;Request.prototype.buffer=Request.prototype.ca;Request.prototype.write=function(){throw new Error("Streaming is not supported in browser version of superagent")};Request.prototype.pipe=Request.prototype.write;Request.prototype._isHost=function(object){return object&&_typeof(object)==="object"&&!Array.isArray(object)&&Object.prototype.toString.call(object)!=="[object Object]"};Request.prototype.end=function(fn){if(this._endCalled){console.warn("Warning: .end() was called twice. This is not supported in superagent")}this._endCalled=true;this._callback=fn||noop;this._finalizeQueryString();this._end()};Request.prototype._setUploadTimeout=function(){var self=this;if(this._uploadTimeout&&!this._uploadTimeoutTimer){this._uploadTimeoutTimer=setTimeout((function(){self._timeoutError("Upload timeout of ",self._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout)}};Request.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));var self=this;this.xhr=request.getXHR();var xhr=this.xhr;var data=this._formData||this._data;this._setTimeouts();xhr.addEventListener("readystatechange",(function(){var readyState=xhr.readyState;if(readyState>=2&&self._responseTimeoutTimer){clearTimeout(self._responseTimeoutTimer)}if(readyState!==4){return}var status;try{status=xhr.status}catch(_unused5){status=0}if(!status){if(self.timedout||self._aborted)return;return self.crossDomainError()}self.emit("end")}));var handleProgress=function handleProgress(direction,e){if(e.total>0){e.percent=e.loaded/e.total*100;if(e.percent===100){clearTimeout(self._uploadTimeoutTimer)}}e.direction=direction;self.emit("progress",e)};if(this.hasListeners("progress")){try{xhr.addEventListener("progress",handleProgress.bind(null,"download"));if(xhr.upload){xhr.upload.addEventListener("progress",handleProgress.bind(null,"upload"))}}catch(_unused6){}}if(xhr.upload){this._setUploadTimeout()}try{if(this.username&&this.password){xhr.open(this.method,this.url,true,this.username,this.password)}else{xhr.open(this.method,this.url,true)}}catch(err){return this.callback(err)}if(this._withCredentials)xhr.withCredentials=true;if(!this._formData&&this.method!=="GET"&&this.method!=="HEAD"&&typeof data!=="string"&&!this._isHost(data)){var contentType=this._header["content-type"];var _serialize=this._serializer||request.serialize[contentType?contentType.split(";")[0]:""];if(!_serialize&&isJSON(contentType)){_serialize=request.serialize["application/json"]}if(_serialize)data=_serialize(data)}for(var field in this.header){if(this.header[field]===null)continue;if(Object.prototype.hasOwnProperty.call(this.header,field))xhr.setRequestHeader(field,this.header[field])}if(this._responseType){xhr.responseType=this._responseType}this.emit("request",this);xhr.send(typeof data==="undefined"?null:data)};request.agent=function(){return new Agent};var _loop=function _loop(){var method=_arr[_i];Agent.prototype[method.toLowerCase()]=function(url,fn){var request_=new request.Request(method,url);this._setDefaults(request_);if(fn){request_.end(fn)}return request_}};for(var _i=0,_arr=["GET","POST","OPTIONS","PATCH","PUT","DELETE"];_i<_arr.length;_i++){_loop()}Agent.prototype.del=Agent.prototype.delete;request.get=function(url,data,fn){var request_=request("GET",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.query(data);if(fn)request_.end(fn);return request_};request.head=function(url,data,fn){var request_=request("HEAD",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.query(data);if(fn)request_.end(fn);return request_};request.options=function(url,data,fn){var request_=request("OPTIONS",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.send(data);if(fn)request_.end(fn);return request_};function del(url,data,fn){var request_=request("DELETE",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.send(data);if(fn)request_.end(fn);return request_}request.del=del;request.delete=del;request.patch=function(url,data,fn){var request_=request("PATCH",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.send(data);if(fn)request_.end(fn);return request_};request.post=function(url,data,fn){var request_=request("POST",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.send(data);if(fn)request_.end(fn);return request_};request.put=function(url,data,fn){var request_=request("PUT",url);if(typeof data==="function"){fn=data;data=null}if(data)request_.send(data);if(fn)request_.end(fn);return request_}},{"./agent-base":231,"./is-object":233,"./request-base":234,"./response-base":235,"component-emitter":58,"fast-safe-stringify":79,qs:176}],233:[function(require,module,exports){"use strict";function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}function isObject(object){return object!==null&&_typeof(object)==="object"}module.exports=isObject},{}],234:[function(require,module,exports){(function(process){(function(){"use strict";function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj},_typeof(obj)}var semver=require("semver");var isObject=require("./is-object");module.exports=RequestBase;function RequestBase(object){if(object)return mixin(object)}function mixin(object){for(var key in RequestBase.prototype){if(Object.prototype.hasOwnProperty.call(RequestBase.prototype,key))object[key]=RequestBase.prototype[key]}return object}RequestBase.prototype.clearTimeout=function(){clearTimeout(this._timer);clearTimeout(this._responseTimeoutTimer);clearTimeout(this._uploadTimeoutTimer);delete this._timer;delete this._responseTimeoutTimer;delete this._uploadTimeoutTimer;return this};RequestBase.prototype.parse=function(fn){this._parser=fn;return this};RequestBase.prototype.responseType=function(value){this._responseType=value;return this};RequestBase.prototype.serialize=function(fn){this._serializer=fn;return this};RequestBase.prototype.timeout=function(options){if(!options||_typeof(options)!=="object"){this._timeout=options;this._responseTimeout=0;this._uploadTimeout=0;return this}for(var option in options){if(Object.prototype.hasOwnProperty.call(options,option)){switch(option){case"deadline":this._timeout=options.deadline;break;case"response":this._responseTimeout=options.response;break;case"upload":this._uploadTimeout=options.upload;break;default:console.warn("Unknown timeout option",option)}}}return this};RequestBase.prototype.retry=function(count,fn){if(arguments.length===0||count===true)count=1;if(count<=0)count=0;this._maxRetries=count;this._retries=0;this._retryCallback=fn;return this};var ERROR_CODES=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]);var STATUS_CODES=new Set([408,413,429,500,502,503,504,521,522,524]);RequestBase.prototype._shouldRetry=function(error,res){if(!this._maxRetries||this._retries++>=this._maxRetries){return false}if(this._retryCallback){try{var override=this._retryCallback(error,res);if(override===true)return true;if(override===false)return false}catch(error_){console.error(error_)}}if(res&&res.status&&STATUS_CODES.has(res.status))return true;if(error){if(error.code&&ERROR_CODES.has(error.code))return true;if(error.timeout&&error.code==="ECONNABORTED")return true;if(error.crossDomain)return true}return false};RequestBase.prototype._retry=function(){this.clearTimeout();if(this.req){this.req=null;this.req=this.request()}this._aborted=false;this.timedout=false;this.timedoutError=null;return this._end()};RequestBase.prototype.then=function(resolve,reject){var _this=this;if(!this._fullfilledPromise){var self=this;if(this._endCalled){console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises")}this._fullfilledPromise=new Promise((function(resolve,reject){self.on("abort",(function(){if(_this._maxRetries&&_this._maxRetries>_this._retries){return}if(_this.timedout&&_this.timedoutError){reject(_this.timedoutError);return}var error=new Error("Aborted");error.code="ABORTED";error.status=_this.status;error.method=_this.method;error.url=_this.url;reject(error)}));self.end((function(error,res){if(error)reject(error);else resolve(res)}))}))}return this._fullfilledPromise.then(resolve,reject)};RequestBase.prototype.catch=function(cb){return this.then(undefined,cb)};RequestBase.prototype.use=function(fn){fn(this);return this};RequestBase.prototype.ok=function(cb){if(typeof cb!=="function")throw new Error("Callback required");this._okCallback=cb;return this};RequestBase.prototype._isResponseOK=function(res){if(!res){return false}if(this._okCallback){return this._okCallback(res)}return res.status>=200&&res.status<300};RequestBase.prototype.get=function(field){return this._header[field.toLowerCase()]};RequestBase.prototype.getHeader=RequestBase.prototype.get;RequestBase.prototype.set=function(field,value){if(isObject(field)){for(var key in field){if(Object.prototype.hasOwnProperty.call(field,key))this.set(key,field[key])}return this}this._header[field.toLowerCase()]=value;this.header[field]=value;return this};RequestBase.prototype.unset=function(field){delete this._header[field.toLowerCase()];delete this.header[field];return this};RequestBase.prototype.field=function(name,value){if(name===null||undefined===name){throw new Error(".field(name, val) name can not be empty")}if(this._data){throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()")}if(isObject(name)){for(var key in name){if(Object.prototype.hasOwnProperty.call(name,key))this.field(key,name[key])}return this}if(Array.isArray(value)){for(var i in value){if(Object.prototype.hasOwnProperty.call(value,i))this.field(name,value[i])}return this}if(value===null||undefined===value){throw new Error(".field(name, val) val can not be empty")}if(typeof value==="boolean"){value=String(value)}this._getFormData().append(name,value);return this};RequestBase.prototype.abort=function(){if(this._aborted){return this}this._aborted=true;if(this.xhr)this.xhr.abort();if(this.req){if(semver.gte(process.version,"v13.0.0")&&semver.lt(process.version,"v14.0.0")){throw new Error("Superagent does not work in v13 properly with abort() due to Node.js core changes")}else if(semver.gte(process.version,"v14.0.0")){this.req.destroyed=true}this.req.abort()}this.clearTimeout();this.emit("abort");return this};RequestBase.prototype._auth=function(user,pass,options,base64Encoder){switch(options.type){case"basic":this.set("Authorization","Basic ".concat(base64Encoder("".concat(user,":").concat(pass))));break;case"auto":this.username=user;this.password=pass;break;case"bearer":this.set("Authorization","Bearer ".concat(user));break;default:break}return this};RequestBase.prototype.withCredentials=function(on){if(on===undefined)on=true;this._withCredentials=on;return this};RequestBase.prototype.redirects=function(n){this._maxRedirects=n;return this};RequestBase.prototype.maxResponseSize=function(n){if(typeof n!=="number"){throw new TypeError("Invalid argument")}this._maxResponseSize=n;return this};RequestBase.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}};RequestBase.prototype.send=function(data){var isObject_=isObject(data);var type=this._header["content-type"];if(this._formData){throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()")}if(isObject_&&!this._data){if(Array.isArray(data)){this._data=[]}else if(!this._isHost(data)){this._data={}}}else if(data&&this._data&&this._isHost(this._data)){throw new Error("Can't merge these send calls")}if(isObject_&&isObject(this._data)){for(var key in data){if(Object.prototype.hasOwnProperty.call(data,key))this._data[key]=data[key]}}else if(typeof data==="string"){if(!type)this.type("form");type=this._header["content-type"];if(type)type=type.toLowerCase().trim();if(type==="application/x-www-form-urlencoded"){this._data=this._data?"".concat(this._data,"&").concat(data):data}else{this._data=(this._data||"")+data}}else{this._data=data}if(!isObject_||this._isHost(data)){return this}if(!type)this.type("json");return this};RequestBase.prototype.sortQuery=function(sort){this._sort=typeof sort==="undefined"?true:sort;return this};RequestBase.prototype._finalizeQueryString=function(){var query=this._query.join("&");if(query){this.url+=(this.url.includes("?")?"&":"?")+query}this._query.length=0;if(this._sort){var index=this.url.indexOf("?");if(index>=0){var queryArray=this.url.slice(index+1).split("&");if(typeof this._sort==="function"){queryArray.sort(this._sort)}else{queryArray.sort()}this.url=this.url.slice(0,index)+"?"+queryArray.join("&")}}};RequestBase.prototype._appendQueryString=function(){console.warn("Unsupported")};RequestBase.prototype._timeoutError=function(reason,timeout,errno){if(this._aborted){return}var error=new Error("".concat(reason+timeout,"ms exceeded"));error.timeout=timeout;error.code="ECONNABORTED";error.errno=errno;this.timedout=true;this.timedoutError=error;this.abort();this.callback(error)};RequestBase.prototype._setTimeouts=function(){var self=this;if(this._timeout&&!this._timer){this._timer=setTimeout((function(){self._timeoutError("Timeout of ",self._timeout,"ETIME")}),this._timeout)}if(this._responseTimeout&&!this._responseTimeoutTimer){this._responseTimeoutTimer=setTimeout((function(){self._timeoutError("Response timeout of ",self._responseTimeout,"ETIMEDOUT")}),this._responseTimeout)}}}).call(this)}).call(this,require("_process"))},{"./is-object":233,_process:174,semver:30}],235:[function(require,module,exports){"use strict";var utils=require("./utils");module.exports=ResponseBase;function ResponseBase(object){if(object)return mixin(object)}function mixin(object){for(var key in ResponseBase.prototype){if(Object.prototype.hasOwnProperty.call(ResponseBase.prototype,key))object[key]=ResponseBase.prototype[key]}return object}ResponseBase.prototype.get=function(field){return this.header[field.toLowerCase()]};ResponseBase.prototype._setHeaderProperties=function(header){var ct=header["content-type"]||"";this.type=utils.type(ct);var parameters=utils.params(ct);for(var key in parameters){if(Object.prototype.hasOwnProperty.call(parameters,key))this[key]=parameters[key]}this.links={};try{if(header.link){this.links=utils.parseLinks(header.link)}}catch(_unused){}};ResponseBase.prototype._setStatusProperties=function(status){var type=Math.trunc(status/100);this.statusCode=status;this.status=this.statusCode;this.statusType=type;this.info=type===1;this.ok=type===2;this.redirect=type===3;this.clientError=type===4;this.serverError=type===5;this.error=type===4||type===5?this.toError():false;this.created=status===201;this.accepted=status===202;this.noContent=status===204;this.badRequest=status===400;this.unauthorized=status===401;this.notAcceptable=status===406;this.forbidden=status===403;this.notFound=status===404;this.unprocessableEntity=status===422}},{"./utils":236}],236:[function(require,module,exports){"use strict";function _createForOfIteratorHelper(o,allowArrayLike){var it=typeof Symbol!=="undefined"&&o[Symbol.iterator]||o["@@iterator"];if(!it){if(Array.isArray(o)||(it=_unsupportedIterableToArray(o))||allowArrayLike&&o&&typeof o.length==="number"){if(it)o=it;var i=0;var F=function F(){};return{s:F,n:function n(){if(i>=o.length)return{done:true};return{done:false,value:o[i++]}},e:function e(_e){throw _e},f:F}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var normalCompletion=true,didErr=false,err;return{s:function s(){it=it.call(o)},n:function n(){var step=it.next();normalCompletion=step.done;return step},e:function e(_e2){didErr=true;err=_e2},f:function f(){try{if(!normalCompletion&&it.return!=null)it.return()}finally{if(didErr)throw err}}}}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen)}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i0);return encoded}function decode(str){var decoded=0;for(i=0;i{this.setSketchFromURL(callback)}));this.setRandomSketch=this.setRandomSketch.bind(this)}clear(){this.current=null;this.code=null;let newurl=window.location.protocol+"//"+window.location.host+window.location.pathname;window.history.pushState({path:newurl},"",newurl);this.url=newurl}setSketchFromURL(callback){hush();render(o0);let searchParams=new URLSearchParams(window.location.search);let base64Code=searchParams.get("code");let sketch_id=searchParams.get("sketch_id");let code="";this.foundSketch=false;if(sketch_id){var sketch=this.getExampleById(sketch_id);if(sketch){this.setSketch(sketch);callback(this.code,false)}else{request.get("/sketchById").query({sketch_id:sketch_id}).end(((err,res)=>{if(err){console.log("err getting sketches",err);this.setSketchFromCode(base64Code,callback)}else{this.sketches=JSON.parse(res.text);if(this.sketches.length>0){this.setSketch(this.sketches[0]);this.foundSketch=true;callback(this.code,this.foundSketch)}else{this.setSketchFromCode(base64Code,callback)}}}))}}else{this.setSketchFromCode(base64Code,callback)}}setSketchFromCode(base64Code,callback){if(base64Code){this.code=this.decodeBase64(base64Code);this.foundSketch=true}else{this.setRandomSketch()}callback(this.code,this.foundSketch)}saveImage(){}setToURL(params){var url_params;if(params.sketch_id){url_params=`sketch_id=${params.sketch_id}`}else{url_params=`sketch_id=${params.sketch_id}&code=${params.code}`}let newurl=window.location.protocol+"//"+window.location.host+window.location.pathname+"?"+url_params;window.history.replaceState({path:newurl},"",newurl);this.url=newurl}encodeBase64(text){return btoa(encodeURIComponent(text))}decodeBase64(base64Code){return decodeURIComponent(atob(base64Code))}setSketch(sketch){this.code=this.decodeBase64(sketch.code);this.current=sketch;this.setToURL(sketch)}setRandomSketch(){if(this.examples.length>0){let index;index=Math.floor(Math.random()*this.examples.length);while(index===this.exampleIndex){index=Math.floor(Math.random()*this.examples.length)}this.exampleIndex=index;this.setSketch(this.examples[index])}else{var startString="osc("+2+Math.floor(Math.pow(10,Math.random()*2))+")";startString+=".color("+Math.random().toFixed(2)+","+Math.random().toFixed(2)+","+Math.random().toFixed(2)+")";startString+=".rotate("+Math.random().toFixed(2)+")";startString+=".out(o0)";this.code=startString}}shareSketch(code,hydra,name){this.saveSketch(code,(()=>{console.log("URL is",this.url,"sketch is",this.current);hydra.getScreenImage((img=>{request.post("/image").attach("previewImage",img).query({url:this.url,sketch_id:this.current.sketch_id,name:name}).end(((err,res)=>{if(err){console.log("error postingimage",err)}else{console.log("image response",res.text)}}))}))}))}saveSketch(code,callback){let self=this;let base64=this.encodeBase64(code);let query={code:base64,parent:this.current?this.current.sketch_id:null};console.log("saving in gallery",query);request.post("/sketch").query(query).end(((err,res)=>{if(err){console.log("error posting sketch",err);if(callback)callback(err)}else{console.log("response",res.text);self.setSketch({sketch_id:res.text,code:base64});if(callback)callback(null)}}))}saveLocally(code){let base64=this.encodeBase64(code);var url_params=`code=${base64}`;let newurl=window.location.protocol+"//"+window.location.host+window.location.pathname+"?"+url_params;window.history.pushState({path:newurl},"",newurl);this.url=newurl}getExampleById(id){var sketches=this.examples.filter((sketch=>sketch.sketch_id===id));if(sketches.length<=0)sketches=this.sketches.filter((sketch=>sketch.sketch_id===id));return sketches[0]}}module.exports=Gallery},{"./examples.json":242,superagent:232}],244:[function(require,module,exports){class P5 extends p5{constructor({width:width=window.innerWidth,height:height=window.innerHeight,mode:mode="P2D"}={}){super((p=>{p.setup=()=>{p.createCanvas(width,height,p[mode])};p.draw=()=>{}}),"hydra-ui");this.width=width;this.height=height;this.mode=mode;this.canvas.style.position="absolute";this.canvas.style.top="0px";this.canvas.style.left="0px";this.canvas.style.zIndex=-1}show(){this.canvas.style.visibility="visible"}hide(){this.canvas.style.visibility="hidden"}clear(){this.drawingContext.clearRect(0,0,this.canvas.width,this.canvas.height)}}module.exports=P5},{}],245:[function(require,module,exports){var PatchBay=require("./rtc-patch-bay.js");var inherits=require("inherits");var PBLive=function(){this.session={};this.nickFromId={};this.idFromNick={};this.loadFromStorage()};inherits(PBLive,PatchBay);PBLive.prototype.init=function(stream,opts){this.settings={server:opts.server||"https://patch-bay.glitch.me/",room:opts.room||"patch-bay",stream:stream};this.makeGlobal=opts.makeGlobal||true;this.setPageTitle=opts.setTitle||true;if(this.session.id)this.settings.id=this.session.id;PatchBay.call(this,this.settings);if(this.makeGlobal)window.pb=this;this.on("ready",(()=>{if(!this.nick){if(this.session.nick){this.setName(this.session.nick)}else{this.session.id=this.id;this.setName(this.session.id)}}console.log("connected to server "+this.settings.server+" with name "+this.settings.id)}));this.on("broadcast",this._processBroadcast.bind(this));this.on("new peer",this.handleNewPeer.bind(this));window.onbeforeunload=()=>{this.session.id=window.pb.id;this.session.nick=this.nick;sessionStorage.setItem("pb",JSON.stringify(this.session))};var self=this;this.on("stream",(function(id,stream){console.log("got stream!",id,stream);const video=document.createElement("video");if("srcObject"in video){video.srcObject=stream}else{video.src=window.URL.createObjectURL(stream)}video.addEventListener("loadedmetadata",(()=>{video.play();self.video=video;self.emit("got video",self.nickFromId[id],video)}))}))};PBLive.prototype.loadFromStorage=function(){if(sessionStorage.getItem("pb")!==null){this.session=JSON.parse(sessionStorage.getItem("pb"))}};PBLive.prototype.initSource=function(nick,callback){this.initConnectionFromId(this.idFromNick[nick],callback)};PBLive.prototype.handleNewPeer=function(peer){this.nickFromId[peer]=peer;this.idFromNick[peer]=peer;if(this.nick){this.broadcast({type:"update-nick",id:this.id,nick:this.nick})}};PBLive.prototype.list=function(){var l=Object.keys(this.idFromNick);return Object.keys(this.idFromNick)};PBLive.prototype.setName=function(nick){this.broadcast({type:"update-nick",id:this.id,nick:nick,previous:this.nick});this.nick=nick;if(this.setPageTitle)document.title=nick};PBLive.prototype._processBroadcast=function(data){if(data.type==="update-nick"){if(data.previous!==data.nick){delete this.idFromNick[this.nickFromId[data.id]];this.nickFromId[data.id]=data.nick;this.idFromNick[data.nick]=data.id;if(data.previous){}else{}}}};module.exports=PBLive},{"./rtc-patch-bay.js":246,inherits:115}],246:[function(require,module,exports){var io=require("socket.io-client");var SimplePeer=require("simple-peer");var extend=Object.assign;var events=require("events").EventEmitter;var inherits=require("inherits");const shortid=require("shortid");var PatchBay=function(options){this.signaller=io(options.server);this.id=options.id||shortid.generate();this.stream=options.stream||null;this._peerOptions=options.peerOptions||{};this._room=options.room;this.settings["shareMediaWhenRequested"]=true;this.settings["shareMediaWhenInitiating"]=false;this.settings["requestMediaWhenInitiating"]=true;this.settings["autoconnect"]=false;this.peers={};this.rtcPeers={};this.signaller.on("ready",this._readyForSignalling.bind(this));this.signaller.on("message",this._handleMessage.bind(this));this.signaller.on("broadcast",this._receivedBroadcast.bind(this));this.signaller.emit("join",this._room,{uuid:this.id});this.signaller.on("new peer",this._newPeer.bind(this))};inherits(PatchBay,events);PatchBay.prototype.sendToAll=function(data){Object.keys(this.rtcPeers).forEach((function(id){this.rtcPeers[id].send(data)}),this)};PatchBay.prototype.sendToPeer=function(peerId,data){if(peerId in this.rtcPeers){this.rtcPeers[peerId].send(data)}};PatchBay.prototype.reinitAll=function(){Object.keys(this.rtcPeers).forEach(function(id){this.reinitPeer(id)}.bind(this))};PatchBay.prototype.initRtcPeer=function(id,opts){this.emit("new peer",{id:id});var newOptions=opts;if(this.iceServers){opts["config"]={iceServers:this.iceServers}}if(opts.initiator===true){if(this.stream!=null){if(this.settings.shareMediaWhenInitiating===true){newOptions.stream=this.stream}}if(this.settings.requestMediaWhenInitiating===true){newOptions.offerConstraints={offerToReceiveVideo:true,offerToReceiveAudio:true}}}else{if(this.settings.shareMediaWhenRequested===true){if(this.stream!=null){newOptions.stream=this.stream}}}var options=extend(this._peerOptions,newOptions);this.rtcPeers[id]=new SimplePeer(options);this._attachPeerEvents(this.rtcPeers[id],id)};PatchBay.prototype.reinitRtcConnection=function(id,opts){this.rtcPeers[id]._destroy(null,function(e){this.initRtcPeer(id,{stream:this.stream,initiator:true})}.bind(this))};PatchBay.prototype._newPeer=function(peer){this.peers[peer]={rtcPeer:null};this.emit("new peer",peer)};PatchBay.prototype._readyForSignalling=function({peers:peers,servers:servers}){peers.forEach((peer=>{this._newPeer(peer)}));if(servers){this.iceServers=servers}this.emit("ready")};PatchBay.prototype.initConnectionFromId=function(id,callback){if(id in this.rtcPeers){console.log("Already connected to..",id,this.rtcPeers);if(this.rtcPeers[id].initiator===false){this.reinitRtcConnection(id)}else{}}else{this.initRtcPeer(id,{initiator:true})}};PatchBay.prototype._handleMessage=function(data){if(data.type==="signal"){this._handleSignal(data)}else{this.emit("message",data)}};PatchBay.prototype._handleSignal=function(data){if(!this.rtcPeers[data.id]){this.initRtcPeer(data.id,{initiator:false})}this.rtcPeers[data.id].signal(data.message)};PatchBay.prototype._receivedBroadcast=function(data){this.emit("broadcast",data)};PatchBay.prototype.broadcast=function(data){this.signaller.emit("broadcast",data)};PatchBay.prototype._attachPeerEvents=function(p,_id){p.on("signal",function(id,signal){this.signaller.emit("message",{id:id,message:signal,type:"signal"})}.bind(this,_id));p.on("stream",function(id,stream){this.rtcPeers[id].stream=stream;this.emit("stream",id,stream)}.bind(this,_id));p.on("connect",function(id){this.emit("connect",id)}.bind(this,_id));p.on("data",function(id,data){this.emit("data",{id:id,data:JSON.parse(data)})}.bind(this,_id));p.on("close",function(id){delete this.rtcPeers[id];this.emit("close",id)}.bind(this,_id));p.on("error",(function(e){console.warn("simple peer error",e)}))};PatchBay.prototype._destroy=function(){Object.values(this.rtcPeers).forEach((function(peer){peer.destroy()}));this.signaller.close()};module.exports=PatchBay},{events:31,inherits:115,shortid:189,"simple-peer":199,"socket.io-client":219}],247:[function(require,module,exports){module.exports={en:{translation:{"language-name":"english",toolbar:{run:"Run all code (ctrl+shift+enter)",upload:"upload to gallery",clear:"clear all",shuffle:"show random sketch",random:"make random change","show-info":"show info window","hide-info":"hide info window"},info:{title:"hydra",subtitle:"live coding networked visuals",description:"Hydra is a platform for live coding visuals, in which each connected browser window can be used as a node of a modular and distributed video synthesizer.","get-started-title":"To get started:","get-started-list":["Close this window","Change some numbers","Type Ctrl + Shift + Enter"],"description-detailed":"Built using WebRTC (peer-to-peer web streaming) and WebGL, hydra allows each connected browser/device/person to output a video signal or stream, and receive and modify streams from other browsers/devices/people. The API is inspired by analog modular synthesis, in which multiple visual sources (oscillators, cameras, application windows, other connected windows) can be transformed, modulated, and composited via combining sequences of functions.",features:"Features:","features-list":["Written in javascript and compatible with other javascript libraries","Available as a platform as well as a set of standalone modules","Cross-platform and requires no installation (runs in the browser)","Also available as a package for live coding from within atom text editor","Experimental and forever evolving !!"],author:"Created by olivia.","more-info":"For more information and instructions, see: the online documentation, a list of hydra functions, the source code on github, a gallery of user-generated sketches, PIXELJAM collaborative editor, Hydra Book, and more tutorials and examples.","more-info-forums":"There is also an active Discord server and facebook group for hydra users+contributors.",support:"If you enjoy using Hydra, please consider supporting continued development <3 ."}}}}},{}],248:[function(require,module,exports){const Gallery=require("./gallery.js");const repl=require("./views/editor/repl.js");const i18next=require("i18next");const i18nextBrowserLanguageDetector=require("i18next-browser-languagedetector");const languageResources=require("./locales.js");i18next.use(i18nextBrowserLanguageDetector).init({debug:true,fallbackLng:"en",resources:languageResources});module.exports=function store(state,emitter){state.showInfo=true;state.showUI=true;const languages={};Object.keys(languageResources).forEach((key=>languages[key]=i18next.getFixedT(key)("language-name")));state.translation={t:i18next.t,languages:languages,selectedLanguage:i18next.language};emitter.on("set language",(lang=>{console.log("setting language to",lang);i18next.changeLanguage(lang,((err,t)=>{console.log(err,t);selectedLanguage=lang;emitter.emit("render")}))}));let sketches;emitter.on("DOMContentLoaded",(function(){const editor=state.editor.editor;sketches=new Gallery(((code,sketchFromURL)=>{editor.setValue(code);repl.eval(code);if(sketchFromURL){state.showInfo=false}else{state.showInfo=true}emitter.emit("render")}))}));emitter.on("editor:randomize",(function(evt){const editor=state.editor.editor;if(evt.shiftKey){editor.mutator.doUndo()}else{editor.mutator.mutate({reroll:false,changeTransform:evt.metaKey});editor.formatCode();sketches.saveLocally(editor.getValue())}}));function clearAll(){const editor=state.editor.editor;hush();speed=1;sketches.clear();editor.clear()}emitter.on("editor:clearAll",(function(){clearAll()}));emitter.on("editor:evalAll",(function(){const editor=state.editor.editor;const code=editor.getValue();repl.eval(code,((string,err)=>{editor.flashCode();if(!err)sketches.saveLocally(code)}))}));emitter.on("editor:evalLine",(line=>{repl.eval(line)}));emitter.on("editor:evalBlock",(block=>{repl.eval(block)}));emitter.on("gallery:shareSketch",(function(){let editor=state.editor.editor;const code=editor.getValue();repl.eval(editor.getValue(),((code,error)=>{if(!error){showConfirmation((name=>{sketches.shareSketch(code,state.hydra.hydra,name)}),(()=>{}))}else{console.warn(error)}}))}));emitter.on("gallery:showExample",(()=>{const editor=state.editor.editor;clearAll();sketches.setRandomSketch();editor.setValue(sketches.code);repl.eval(editor.getValue())}));emitter.on("show confirmation",(function(count){}));emitter.on("clear all",(function(count){}));emitter.on("hideAll",(function(){state.showUI=!state.showUI;emitter.emit("render")}));emitter.on("toggle info",(function(count){state.showInfo=!state.showInfo;emitter.emit("render")}));emitter.on("mutate sketch",(function(){}))};function showConfirmation(successCallback,terminateCallback){var c=prompt("Pressing OK will share this sketch to \nhttps://twitter.com/hydra_patterns.\n\nInclude your name or twitter handle (optional):");if(c!==null){successCallback(c)}else{terminateCallback()}}},{"./gallery.js":243,"./locales.js":247,"./views/editor/repl.js":256,i18next:113,"i18next-browser-languagedetector":112}],249:[function(require,module,exports){const html=require("choo/html");const Component=require("choo/component");const HydraEditor=require("./editor/editor.js");const log=require("./editor/log.js");module.exports=class Editor extends Component{constructor(id,state,emit){super(id);this.local=state.components[id]={};state.editor=this;this.emit=emit}load(element){log.init(this.logElement);this.editor=new HydraEditor(this.textEl);this.editor.on("*",((e,args)=>{this.emit(e,args)}));this.innerText=document.getElementsByClassName("CodeMirror")[0]}hide(){this.innerText.style.opacity=0}show(){this.innerText.style.opacity=1;this.innerText.style.pointerEvents="all"}update(state){if(state.showInfo===true||state.showUI===false){this.hide()}else{this.show()}return false}createElement({width:width=window.innerWidth,height:height=window.innerHeight}={}){this.textEl=html` `;this.logElement=html`
`;return html`
${this.textEl}
${this.logElement}
`}}},{"./editor/editor.js":251,"./editor/log.js":253,"choo/component":46,"choo/html":47}],250:[function(require,module,exports){const html=require("choo/html");const Component=require("choo/component");const HydraSynth=require("hydra-synth");const P5=require("./../lib/p5-wrapper.js");const PatchBay=require("./../lib/patch-bay/pb-live.js");module.exports=class Hydra extends Component{constructor(id,state,emit){super(id);this.local=state.components[id]={};state.hydra=this;this.emit=emit}load(element){let isIOS=(/iPad|iPhone|iPod/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1)&&!window.MSStream;let precisionValue=isIOS?"highp":"mediump";const pb=new PatchBay;const hydra=new HydraSynth({pb:pb,detectAudio:true,canvas:element.querySelector("canvas"),precision:precisionValue});console.log(hydra);this.hydra=hydra;osc().out();pb.init(hydra.captureStream,{server:window.location.origin,room:"iclc"});window.P5=P5;window.pb=pb;this.emit("hydra loaded")}update(center){return false}createElement({width:width=window.innerWidth,height:height=window.innerHeight}={}){return html`
`}}},{"./../lib/p5-wrapper.js":244,"./../lib/patch-bay/pb-live.js":245,"choo/component":46,"choo/html":47,"hydra-synth":91}],251:[function(require,module,exports){var CodeMirror=require("codemirror-minified/lib/codemirror");require("codemirror-minified/mode/javascript/javascript");require("codemirror-minified/addon/hint/javascript-hint");require("codemirror-minified/addon/hint/show-hint");require("codemirror-minified/addon/selection/mark-selection");require("codemirror-minified/addon/comment/comment");const EventEmitter=require("nanobus");const keymaps=require("./keymaps.js");const Mutator=require("./randomizer/Mutator.js");const beautify_js=require("js-beautify").js_beautify;var isShowing=true;module.exports=class Editor extends EventEmitter{constructor(parent){super();console.log("*** Editor class created");var self=this;this.mutator=new Mutator(this);const extraKeys={};Object.entries(keymaps).forEach((([key,e])=>extraKeys[key]=()=>{if(e=="editor:evalBlock"){this.emit(e,this.getCurrentBlock().text)}else if(e=="editor:evalLine"){this.emit(e,this.getLine())}else if(e=="editor:toggleComment"){this.cm.toggleComment();this.emit(e,this)}else if(e==="editor:formatCode"){this.formatCode()}else{this.emit(e,this)}}));const opts={theme:"tomorrow-night-eighties",value:"hello",mode:{name:"javascript",globalVars:true},lineWrapping:true,styleSelectedText:true,extraKeys:extraKeys};this.cm=CodeMirror.fromTextArea(parent,opts);window.cm=this.cm;this.cm.refresh()}clear(){this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter')}setValue(val){this.cm.setValue(val)}getValue(){return this.cm.getValue()}formatCode(){const formatted=beautify_js(this.cm.getValue(),{indent_size:2,break_chained_methods:true,indent_with_tabs:true});this.cm.setValue(formatted)}toggle(){if(this.isShowing){this.hide()}else{this.show()}}getLine(){var c=this.cm.getCursor();var s=this.cm.getLine(c.line);this.flashCode({line:c.line,ch:0},{line:c.line+1,ch:0});return s}flashCode(start,end){if(!start)start={line:this.cm.firstLine(),ch:0};if(!end)end={line:this.cm.lastLine()+1,ch:0};var marker=this.cm.markText(start,end,{className:"styled-background"});setTimeout((()=>marker.clear()),300)}getCurrentBlock(){var editor=this.cm;var pos=editor.getCursor();var startline=pos.line;var endline=pos.line;while(startline>0&&editor.getLine(startline)!==""){startline--}while(endline{logElement=el},log:(msg,className="")=>{console.log("logging",msg,className);if(logElement)logElement.innerHTML=` >> ${msg} `},hide:()=>{if(logElement)logElement.style.display="none"},show:()=>{if(logElement)logElement.style.display="block"},toggle:()=>{if(logElement.style.display=="none"){logElement.style.display="block"}else{logElement.style.display="none"}}}},{}],254:[function(require,module,exports){const{Parser:Parser}=require("acorn");const{generate:generate}=require("astring");const{defaultTraveler:defaultTraveler,attachComments:attachComments,makeTraveler:makeTraveler}=require("astravel");const{UndoStack:UndoStack}=require("./UndoStack.js");const repl=require("./../repl.js");const glslTransforms=require("hydra-synth/src/glsl/glsl-functions.js")();class Mutator{constructor(editor){this.editor=editor;this.undoStack=new UndoStack;this.initialVector=[];this.funcTab={};this.transMap={};this.scanFuncs();this.dumpDict()}dumpList(){let gslTab=glslTransforms;gslTab.forEach((v=>{var argList="";v.inputs.forEach((a=>{if(argList!="")argList+=", ";let argL=a.name+": "+a.type+" {"+a.default+"}";argList=argList+argL}))}))}scanFuncs(){let gslTab=glslTransforms;gslTab.forEach((f=>{this.transMap[f.name]=f;if(this.funcTab[f.type]===undefined){this.funcTab[f.type]=[]}this.funcTab[f.type].push(f)}))}dumpDict(){for(let tn in this.funcTab){this.funcTab[tn].forEach((f=>{var argList="";f.inputs.forEach((a=>{if(argList!="")argList+=", ";let argL=a.name+": "+a.type+" {"+a.default+"}";argList=argList+argL}))}))}}mutate(options){let text=this.editor.cm.getValue();this.undoStack.push({text:text,lastLitX:this.lastLitX});let needToRun=true;let tryCounter=5;while(needToRun&&tryCounter-- >=0){var comments=[];let ast=Parser.parse(text,{locations:true,onComment:comments});this.transform(ast,options);attachComments(ast,comments);let regen=generate(ast,{comments:true});this.editor.cm.setValue(regen);try{repl.eval(regen,((code,error)=>{if(error){console.log("Eval error: "+regen)}needToRun=error}))}catch(err){console.log("Exception caught: "+err);needToRun=err}}}doUndo(){if(this.undoStack.atTop()){let text=this.editor.cm.getValue();this.undoStack.push({text:text,lastLitX:this.lastLitX})}if(this.undoStack.canUndo()){let{text:text,lastLitX:lastLitX}=this.undoStack.undo();this.setText(text);this.lastLitX=lastLitX}}doRedo(){if(this.undoStack.canRedo()){let{text:text,lastLitX:lastLitX}=this.undoStack.redo();this.setText(text);this.lastLitX=lastLitX}}setText(text){this.editor.cm.setValue(text);repl.eval(text,((code,error)=>{}))}transform(ast,options){let traveler=makeTraveler({go:function(node,state){if(node.type==="Literal"){state.literalTab.push(node)}else if(node.type==="MemberExpression"){if(node.property&&node.property.type==="Literal"){return}}else if(node.type==="CallExpression"){if(node.callee&&node.callee.property&&node.callee.property.name&&node.callee.property.name!=="out"){state.functionTab.push(node)}}this.super.go.call(this,node,state)}});let state={};state.literalTab=[];state.functionTab=[];traveler.go(ast,state);this.litCount=state.literalTab.length;this.funCount=state.functionTab.length;if(this.litCount!==this.initialVector.length){let nextVect=[];for(let i=0;i0}canRedo(){if(this.stack.length===0||this.index===-1)return false;return this.index=0){while(this.indexthis.limit){this.stack.shift()}this.stack.push(item)}undo(){if(this.stack.length===0)return undefined;if(this.index===-1){this.index=this.stack.length-1}if(this.index>0)this.index--;let v=this.stack[this.index];return v}redo(){if(this.stack.length===0||this.index===-1)return undefined;let nextX=this.index+1;if(nextX>=this.stack.length)return undefined;this.index=nextX;return this.stack[this.index]}}module.exports={UndoStack:UndoStack}},{}],256:[function(require,module,exports){const log=require("./log.js").log;module.exports={eval:(arg,callback)=>{var self=this;var jsString=`(async() => {\n ${arg}\n})().catch(${err=>log(err.message,"log-error")})`;var isError=false;try{eval(jsString);log("")}catch(e){isError=true;console.log("logging",e);log(e.message,"log-error")}if(callback)callback(jsString,isError)}}},{"./log.js":253}],257:[function(require,module,exports){const html=require("choo/html");const raw=require("choo/html/raw");const toolbar=require("./toolbar.js");const link=url=>`href=${url} target=_blank`;module.exports=function mainView(state,emit){const{t:t,languages:languages}=state.translation;const langArray=Object.entries(languages);return html`
`}},{"./toolbar.js":259,"choo/html":47,"choo/html/raw":48}],258:[function(require,module,exports){const html=require("choo/html");const info=require("./info.js");const Hydra=require("./Hydra.js");const Editor=require("./EditorComponent.js");module.exports=function mainView(state,emit){return html`
${state.cache(Hydra,"hydra-canvas").render(state,emit)}
${info(state,emit)} ${state.cache(Editor,"editor").render(state,emit)} `}},{"./EditorComponent.js":249,"./Hydra.js":250,"./info.js":257,"choo/html":47}],259:[function(require,module,exports){const html=require("choo/html");module.exports=function toolbar(state,emit){const hidden=state.showInfo?"hidden":"";const{t:t}=state.translation;const dispatch=eventName=>e=>emit(eventName,e);const icon=(id,className,title,event)=>html` `;const toggleInfo=state.showInfo?icon("close","fa-times",t("toolbar.hide-info"),"toggle info"):icon("close","fa-question-circle",t("toolbar.show-info"),"toggle info");return html`
${icon("run",`fa-play-circle ${hidden}`,t("toolbar.run"),"editor:evalAll")} ${icon("share",`fa-upload ${hidden}`,t("toolbar.upload"),"gallery:shareSketch")} ${icon("clear",`fa fa-trash ${hidden}`,t("toolbar.clear"),"editor:clearAll")} ${icon("shuffle",`fa-random`,t("toolbar.shuffle"),"gallery:showExample")} ${icon("mutator",`fa-dice ${hidden}`,t("toolbar.random"),"editor:randomize")} ${toggleInfo}
`}},{"choo/html":47}]},{},[1]);