(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;i1)&&!window.MSStream;let precisionValue=isIOS?"highp":"mediump";var pb=new PatchBay;var hydra=new HydraSynth({pb:pb,canvas:canvas,autoLoop:false,precision:precisionValue});var editor=new Editor;var menu=new Menu({editor:editor,hydra:hydra});log.init();window.hush=()=>{solid().out();solid().out(o1);solid().out(o2);solid().out(o3);render(o0)};window.loadScript=(url="")=>{const p=new Promise(((res,rej)=>{var script=document.createElement("script");script.onload=function(){log.log(`loaded script ${url}`);res()};script.onerror=err=>{log.log(`error loading script ${url}`,"log-error");res()};script.src=url;document.head.appendChild(script)}));return p};var sketches=new Gallery((function(code,sketchFromURL){editor.setValue(code);repl.eval(code);if(sketchFromURL){menu.closeModal()}else{menu.openModal()}}));menu.sketches=sketches;keymaps.init({editor:editor,gallery:sketches,menu:menu,repl:repl,log:log});pb.init(hydra.captureStream,{server:window.location.origin,room:"iclc"});var engine=loop((function(dt){hydra.tick(dt)})).start()}window.onload=init},{"./keymaps.js":2,"./src/editor.js":5,"./src/gallery.js":7,"./src/log.js":8,"./src/menu.js":9,"./src/p5-wrapper.js":10,"./src/pb-live.js":11,"./src/repl.js":12,"hydra-synth":60,"raf-loop":113}],2:[function(require,module,exports){module.exports={init:({editor:editor,gallery:gallery,menu:menu,repl:repl,log:log})=>{window.onkeydown=e=>{if(e.ctrlKey===true){if(e.shiftKey===true){if(e.keyCode===13){e.preventDefault();menu.runAll()}if(e.keyCode===71){e.preventDefault();menu.shareSketch()}if(e.keyCode===70){e.preventDefault();menu.formatCode()}if(e.keyCode===76){e.preventDefault();gallery.saveLocally(editor.getValue())}if(e.keyCode===72){e.preventDefault();editor.toggle();log.toggle()}if(e.keyCode===83){e.preventDefault();screencap()}}else{if(e.keyCode===13){e.preventDefault();repl.eval(editor.getLine())}if(e.keyCode===191){e.preventDefault();editor.cm.toggleComment()}}}if(e.altKey===true){if(e.keyCode===13){e.preventDefault();repl.eval(editor.getCurrentBlock().text)}}}}}},{}],3:[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}},{}],5:[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");var Mutator=require("./Mutator.js");var isShowing=true;var EditorClass=function(){console.log("*** Editor class created");var self=this;var container=document.createElement("div");container.setAttribute("id","editor-container");var el=document.createElement("TEXTAREA");document.body.appendChild(container);container.appendChild(el);this.mutator=new Mutator(this);this.cm=CodeMirror.fromTextArea(el,{theme:"tomorrow-night-eighties",value:"hello",mode:{name:"javascript",globalVars:true},lineWrapping:true,styleSelectedText:true});this.cm.refresh();this.show();let searchParams=new URLSearchParams(window.location.search);let showCode=searchParams.get("show-code");if(showCode=="false"){var l=document.getElementsByClassName("CodeMirror-scroll")[0];l.style.display="none";isShowing=false}};EditorClass.prototype.clear=function(){this.cm.setValue('\n \n // Type some code on a new line (such as "osc().out()"), and press CTRL+shift+enter')};EditorClass.prototype.setValue=function(val){this.cm.setValue(val)};EditorClass.prototype.getValue=function(){return this.cm.getValue()};EditorClass.prototype.hide=function(){var l=document.getElementsByClassName("CodeMirror-scroll")[0];var m=document.getElementById("modal-header");l.style.display="none";m.style.display="none";this.isShowing=false};EditorClass.prototype.show=function(){var l=document.getElementsByClassName("CodeMirror-scroll")[0];var m=document.getElementById("modal-header");l.style.display="block";m.style.display="flex";this.isShowing=true};EditorClass.prototype.toggle=function(){if(this.isShowing){this.hide()}else{this.show()}};EditorClass.prototype.getLine=function(){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};EditorClass.prototype.flashCode=function(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)};EditorClass.prototype.getCurrentBlock=function(){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{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":6,superagent:157}],8:[function(require,module,exports){var logElement;module.exports={init:()=>{logElement=document.createElement("div");logElement.className="console cm-s-tomorrow-night-eighties";document.body.appendChild(logElement)},log:(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"}}}},{}],9:[function(require,module,exports){const repl=require("./repl.js");const beautify_js=require("js-beautify").js_beautify;class Menu{constructor(obj){this.sketches=obj.sketches;this.editor=obj.editor;this.hydra=obj.hydra;this.closeButton=document.getElementById("close-icon");this.clearButton=document.getElementById("clear-icon");this.shareButton=document.getElementById("share-icon");this.shuffleButton=document.getElementById("shuffle-icon");this.mutatorButton=document.getElementById("mutator-icon");this.runButton=document.getElementById("run-icon");this.editorText=document.getElementsByClassName("CodeMirror-scroll")[0];this.runButton.onclick=this.runAll.bind(this);this.shuffleButton.onclick=this.shuffleSketches.bind(this);this.shareButton.onclick=this.shareSketch.bind(this);this.clearButton.onclick=this.clearAll.bind(this);this.closeButton.onclick=()=>{if(!this.isClosed){this.closeModal()}else{this.openModal()}};this.mutatorButton.onclick=this.mutateSketch.bind(this);this.isClosed=false;this.closeModal()}runAll(){repl.eval(this.editor.getValue(),((string,err)=>{this.editor.flashCode();if(!err)this.sketches.saveLocally(this.editor.getValue())}))}shuffleSketches(){this.clearAll();this.sketches.setRandomSketch();this.editor.setValue(this.sketches.code);repl.eval(this.editor.getValue())}formatCode(){const formatted=beautify_js(this.editor.getValue(),{indent_size:2,break_chained_methods:true,indent_with_tabs:true});this.editor.setValue(formatted)}shareSketch(){repl.eval(this.editor.getValue(),((code,error)=>{if(!error){this.showConfirmation((name=>{this.sketches.shareSketch(code,this.hydra,name)}),(()=>this.hideConfirmation()))}else{console.warn(error)}}))}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()}}hideConfirmation(){}clearAll(){hush();speed=1;this.sketches.clear();this.editor.clear()}closeModal(){document.getElementById("info-container").className="hidden";this.closeButton.className="fas fa-question-circle icon";this.shareButton.classList.remove("hidden");this.clearButton.classList.remove("hidden");this.mutatorButton.classList.remove("hidden");this.runButton.classList.remove("hidden");this.editorText.style.opacity=1;this.isClosed=true}openModal(){document.getElementById("info-container").className="";this.closeButton.className="fas fa-times icon";this.shareButton.classList.add("hidden");this.clearButton.classList.add("hidden");this.mutatorButton.classList.add("hidden");this.runButton.classList.add("hidden");this.editorText.style.opacity=0;this.isClosed=false}mutateSketch(evt){if(evt.shiftKey){this.editor.mutator.doUndo()}else{this.editor.mutator.mutate({reroll:false,changeTransform:evt.metaKey});this.formatCode();this.sketches.saveLocally(this.editor.getValue())}}}module.exports=Menu},{"./repl.js":12,"js-beautify":83}],10:[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},{}],11:[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":13,inherits:80}],12:[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":8}],13:[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:26,inherits:80,shortid:128,"simple-peer":138,"socket.io-client":142}],14:[function(require,module,exports){(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?factory(exports):typeof define==="function"&&define.amd?define(["exports"],factory):(global=global||self,factory(global.acorn={}))})(this,(function(exports){"use strict";var reservedWords={3:"abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",5:"class enum extends super const export import",6:"enum",strict:"implements interface let package private protected public static yield",strictBind:"eval arguments"};var ecma5AndLessKeywords="break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";var keywords={5:ecma5AndLessKeywords,"5module":ecma5AndLessKeywords+" export import",6:ecma5AndLessKeywords+" const class extends export import super"};var keywordRelationalOperator=/^in(stanceof)?$/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࢠ-ࢴࢶ-ࣇऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲈᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-鿼ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞿꟂ-ꟊꟵ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛࣓-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿᫀᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷹᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");nonASCIIidentifierStartChars=nonASCIIidentifierChars=null;var astralIdentifierStartCodes=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];var astralIdentifierCodes=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];function isInAstralSet(code,set){var pos=65536;for(var i=0;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$1={};function kw(name,options){if(options===void 0)options={};options.keyword=name;return keywords$1[name]=new TokenType(name,options)}var types={num:new TokenType("num",startsExpr),regexp:new TokenType("regexp",startsExpr),string:new TokenType("string",startsExpr),name:new TokenType("name",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,ecma2019String){return code===10||code===13||!ecma2019String&&(code===8232||code===8233)}var nonASCIIwhitespace=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var skipWhiteSpace=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;var ref=Object.prototype;var hasOwnProperty=ref.hasOwnProperty;var toString=ref.toString;function has(obj,propName){return hasOwnProperty.call(obj,propName)}var isArray=Array.isArray||function(obj){return toString.call(obj)==="[object Array]"};function wordsRegexp(words){return new RegExp("^(?:"+words.replace(/ /g,"|")+")$")}var Position=function Position(line,col){this.line=line;this.column=col};Position.prototype.offset=function offset(n){return new Position(this.line,this.column+n)};var SourceLocation=function SourceLocation(p,start,end){this.start=start;this.end=end;if(p.sourceFile!==null){this.source=p.sourceFile}};function getLineInfo(input,offset){for(var line=1,cur=0;;){lineBreakG.lastIndex=cur;var match=lineBreakG.exec(input);if(match&&match.index=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_VAR=SCOPE_TOP|SCOPE_FUNCTION,SCOPE_ASYNC=4,SCOPE_GENERATOR=8,SCOPE_ARROW=16,SCOPE_SIMPLE_CATCH=32,SCOPE_SUPER=64,SCOPE_DIRECT_SUPER=128;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[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.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.yieldPos=this.awaitPos=this.awaitIdentPos=0;this.labels=[];this.undefinedExports={};if(this.pos===0&&options.allowHashBang&&this.input.slice(0,2)==="#!"){this.skipLineComment(2)}this.scopeStack=[];this.enterScope(SCOPE_TOP);this.regexpState=null};var prototypeAccessors={inFunction:{configurable:true},inGenerator:{configurable:true},inAsync:{configurable:true},allowSuper:{configurable:true},allowDirectSuper:{configurable:true},treatFunctionsAsVar:{configurable:true},inNonArrowFunction:{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};prototypeAccessors.inAsync.get=function(){return(this.currentVarScope().flags&SCOPE_ASYNC)>0};prototypeAccessors.allowSuper.get=function(){return(this.currentThisScope().flags&SCOPE_SUPER)>0};prototypeAccessors.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SCOPE_DIRECT_SUPER)>0};prototypeAccessors.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())};prototypeAccessors.inNonArrowFunction.get=function(){return(this.currentThisScope().flags&SCOPE_FUNCTION)>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.eat=function(type){if(this.type===type){this.next();return true}else{return false}};pp.isContextual=function(name){return this.type===types.name&&this.value===name&&!this.containsEsc};pp.eatContextual=function(name){if(!this.isContextual(name)){return false}this.next();return true};pp.expectContextual=function(name){if(!this.eatContextual(name)){this.unexpected()}};pp.canInsertSemicolon=function(){return this.type===types.eof||this.type===types.braceR||lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp.insertSemicolon=function(){if(this.canInsertSemicolon()){if(this.options.onInsertedSemicolon){this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc)}return true}};pp.semicolon=function(){if(!this.eat(types.semi)&&!this.insertSemicolon()){this.unexpected()}};pp.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.expect=function(type){this.eat(type)||this.unexpected()};pp.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.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.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.checkYieldAwaitInDefaultParams=function(){if(this.yieldPos&&(!this.awaitPos||this.yieldPos=6){this.unexpected()}return this.parseFunctionStatement(node,false,!context);case types._class:if(context){this.unexpected()}return this.parseClass(node,true);case types._if:return this.parseIfStatement(node);case types._return:return this.parseReturnStatement(node);case types._switch:return this.parseSwitchStatement(node);case types._throw:return this.parseThrowStatement(node);case types._try:return this.parseTryStatement(node);case types._const:case types._var:kind=kind||this.value;if(context&&kind!=="var"){this.unexpected()}return this.parseVarStatement(node,kind);case types._while:return this.parseWhileStatement(node);case types._with:return this.parseWithStatement(node);case types.braceL:return this.parseBlock(true,node);case types.semi:return this.parseEmptyStatement(node);case types._export:case types._import:if(this.options.ecmaVersion>10&&starttype===types._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._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.name&&expr.type==="Identifier"&&this.eat(types.colon)){return this.parseLabeledStatement(node,maybeName,expr,context)}else{return this.parseExpressionStatement(node,expr)}}};pp$1.parseBreakContinueStatement=function(node,keyword){var isBreak=keyword==="break";this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.label=null}else if(this.type!==types.name){this.unexpected()}else{node.label=this.parseIdent();this.semicolon()}var i=0;for(;i=6){this.eat(types.semi)}else{this.semicolon()}return this.finishNode(node,"DoWhileStatement")};pp$1.parseForStatement=function(node){this.next();var awaitAt=this.options.ecmaVersion>=9&&(this.inAsync||!this.inFunction&&this.options.allowAwaitOutsideFunction)&&this.eatContextual("await")?this.lastTokStart:-1;this.labels.push(loopLabel);this.enterScope(0);this.expect(types.parenL);if(this.type===types.semi){if(awaitAt>-1){this.unexpected(awaitAt)}return this.parseFor(node,null)}var isLet=this.isLet();if(this.type===types._var||this.type===types._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._in||this.options.ecmaVersion>=6&&this.isContextual("of"))&&init$1.declarations.length===1){if(this.options.ecmaVersion>=9){if(this.type===types._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 refDestructuringErrors=new DestructuringErrors;var init=this.parseExpression(true,refDestructuringErrors);if(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of")){if(this.options.ecmaVersion>=9){if(this.type===types._in){if(awaitAt>-1){this.unexpected(awaitAt)}}else{node.await=awaitAt>-1}}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$1.parseFunctionStatement=function(node,isAsync,declarationPosition){this.next();return this.parseFunction(node,FUNC_STATEMENT|(declarationPosition?0:FUNC_HANGING_STATEMENT),false,isAsync)};pp$1.parseIfStatement=function(node){this.next();node.test=this.parseParenExpression();node.consequent=this.parseStatement("if");node.alternate=this.eat(types._else)?this.parseStatement("if"):null;return this.finishNode(node,"IfStatement")};pp$1.parseReturnStatement=function(node){if(!this.inFunction&&!this.options.allowReturnOutsideFunction){this.raise(this.start,"'return' outside of function")}this.next();if(this.eat(types.semi)||this.insertSemicolon()){node.argument=null}else{node.argument=this.parseExpression();this.semicolon()}return this.finishNode(node,"ReturnStatement")};pp$1.parseSwitchStatement=function(node){this.next();node.discriminant=this.parseParenExpression();node.cases=[];this.expect(types.braceL);this.labels.push(switchLabel);this.enterScope(0);var cur;for(var sawDefault=false;this.type!==types.braceR;){if(this.type===types._case||this.type===types._default){var isCase=this.type===types._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.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$1.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=[];pp$1.parseTryStatement=function(node){this.next();node.block=this.parseBlock();node.handler=null;if(this.type===types._catch){var clause=this.startNode();this.next();if(this.eat(types.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.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._finally)?this.parseBlock():null;if(!node.handler&&!node.finalizer){this.raise(node.start,"Missing catch or finally clause")}return this.finishNode(node,"TryStatement")};pp$1.parseVarStatement=function(node,kind){this.next();this.parseVar(node,false,kind);this.semicolon();return this.finishNode(node,"VariableDeclaration")};pp$1.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$1.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$1.parseEmptyStatement=function(node){this.next();return this.finishNode(node,"EmptyStatement")};pp$1.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$1.parseExpressionStatement=function(node,expr){node.expression=expr;this.semicolon();return this.finishNode(node,"ExpressionStatement")};pp$1.parseBlock=function(createNewLexicalScope,node,exitStrict){if(createNewLexicalScope===void 0)createNewLexicalScope=true;if(node===void 0)node=this.startNode();node.body=[];this.expect(types.braceL);if(createNewLexicalScope){this.enterScope(0)}while(this.type!==types.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$1.parseFor=function(node,init){node.init=init;this.expect(types.semi);node.test=this.type===types.semi?null:this.parseExpression();this.expect(types.semi);node.update=this.type===types.parenR?null:this.parseExpression();this.expect(types.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,"ForStatement")};pp$1.parseForIn=function(node,init){var isForIn=this.type===types._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.parenR);node.body=this.parseStatement("for");this.exitScope();this.labels.pop();return this.finishNode(node,isForIn?"ForInStatement":"ForOfStatement")};pp$1.parseVar=function(node,isFor,kind){node.declarations=[];node.kind=kind;for(;;){var decl=this.startNode();this.parseVarId(decl,kind);if(this.eat(types.eq)){decl.init=this.parseMaybeAssign(isFor)}else if(kind==="const"&&!(this.type===types._in||this.options.ecmaVersion>=6&&this.isContextual("of"))){this.unexpected()}else if(decl.id.type!=="Identifier"&&!(isFor&&(this.type===types._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.comma)){break}}return node};pp$1.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$1.parseFunction=function(node,statement,allowExpressionBody,isAsync){this.initFunction(node);if(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!isAsync){if(this.type===types.star&&statement&FUNC_HANGING_STATEMENT){this.unexpected()}node.generator=this.eat(types.star)}if(this.options.ecmaVersion>=8){node.async=!!isAsync}if(statement&FUNC_STATEMENT){node.id=statement&FUNC_NULLABLE_ID&&this.type!==types.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.name?this.parseIdent():null}this.parseFunctionParams(node);this.parseFunctionBody(node,allowExpressionBody,false);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,statement&FUNC_STATEMENT?"FunctionDeclaration":"FunctionExpression")};pp$1.parseFunctionParams=function(node){this.expect(types.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams()};pp$1.parseClass=function(node,isStatement){this.next();var oldStrict=this.strict;this.strict=true;this.parseClassId(node,isStatement);this.parseClassSuper(node);var classBody=this.startNode();var hadConstructor=false;classBody.body=[];this.expect(types.braceL);while(this.type!==types.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}}}this.strict=oldStrict;this.next();node.body=this.finishNode(classBody,"ClassBody");return this.finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")};pp$1.parseClassElement=function(constructorAllowsSuper){var this$1=this;if(this.eat(types.semi)){return null}var method=this.startNode();var tryContextual=function(k,noLineBreak){if(noLineBreak===void 0)noLineBreak=false;var start=this$1.start,startLoc=this$1.startLoc;if(!this$1.eatContextual(k)){return false}if(this$1.type!==types.parenL&&(!noLineBreak||!this$1.canInsertSemicolon())){return true}if(method.key){this$1.unexpected()}method.computed=false;method.key=this$1.startNodeAt(start,startLoc);method.key.name=k;this$1.finishNode(method.key,"Identifier");return false};method.kind="method";method.static=tryContextual("static");var isGenerator=this.eat(types.star);var isAsync=false;if(!isGenerator){if(this.options.ecmaVersion>=8&&tryContextual("async",true)){isAsync=true;isGenerator=this.options.ecmaVersion>=9&&this.eat(types.star)}else if(tryContextual("get")){method.kind="get"}else if(tryContextual("set")){method.kind="set"}}if(!method.key){this.parsePropertyName(method)}var key=method.key;var allowsDirectSuper=false;if(!method.computed&&!method.static&&(key.type==="Identifier"&&key.name==="constructor"||key.type==="Literal"&&key.value==="constructor")){if(method.kind!=="method"){this.raise(key.start,"Constructor can't have get/set modifier")}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")}method.kind="constructor";allowsDirectSuper=constructorAllowsSuper}else if(method.static&&key.type==="Identifier"&&key.name==="prototype"){this.raise(key.start,"Classes may not have a static property named prototype")}this.parseClassMethod(method,isGenerator,isAsync,allowsDirectSuper);if(method.kind==="get"&&method.value.params.length!==0){this.raiseRecoverable(method.value.start,"getter should have no params")}if(method.kind==="set"&&method.value.params.length!==1){this.raiseRecoverable(method.value.start,"setter should have exactly one param")}if(method.kind==="set"&&method.value.params[0].type==="RestElement"){this.raiseRecoverable(method.value.params[0].start,"Setter cannot use rest params")}return method};pp$1.parseClassMethod=function(method,isGenerator,isAsync,allowsDirectSuper){method.value=this.parseMethod(isGenerator,isAsync,allowsDirectSuper);return this.finishNode(method,"MethodDefinition")};pp$1.parseClassId=function(node,isStatement){if(this.type===types.name){node.id=this.parseIdent();if(isStatement){this.checkLValSimple(node.id,BIND_LEXICAL,false)}}else{if(isStatement===true){this.unexpected()}node.id=null}};pp$1.parseClassSuper=function(node){node.superClass=this.eat(types._extends)?this.parseExprSubscripts():null};pp$1.parseExport=function(node,exports){this.next();if(this.eat(types.star)){if(this.options.ecmaVersion>=11){if(this.eatContextual("as")){node.exported=this.parseIdent(true);this.checkExport(exports,node.exported.name,this.lastTokStart)}else{node.exported=null}}this.expectContextual("from");if(this.type!==types.string){this.unexpected()}node.source=this.parseExprAtom();this.semicolon();return this.finishNode(node,"ExportAllDeclaration")}if(this.eat(types._default)){this.checkExport(exports,"default",this.lastTokStart);var isAsync;if(this.type===types._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._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.string){this.unexpected()}node.source=this.parseExprAtom()}else{for(var i=0,list=node.specifiers;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._function)){return this.parseFunction(this.startNodeAt(startPos,startLoc),0,false,true)}if(canBeArrow&&!this.canInsertSemicolon()){if(this.eat(types.arrow)){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],false)}if(this.options.ecmaVersion>=8&&id.name==="async"&&this.type===types.name&&!containsEsc){id=this.parseIdent(false);if(this.canInsertSemicolon()||!this.eat(types.arrow)){this.unexpected()}return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),[id],true)}}return id;case types.regexp:var value=this.value;node=this.parseLiteral(value.value);node.regex={pattern:value.pattern,flags:value.flags};return node;case types.num:case types.string:return this.parseLiteral(this.value);case types._null:case types._true:case types._false:node=this.startNode();node.value=this.type===types._null?null:this.type===types._true;node.raw=this.type.keyword;this.next();return this.finishNode(node,"Literal");case types.parenL:var start=this.start,expr=this.parseParenAndDistinguishExpression(canBeArrow);if(refDestructuringErrors){if(refDestructuringErrors.parenthesizedAssign<0&&!this.isSimpleAssignTarget(expr)){refDestructuringErrors.parenthesizedAssign=start}if(refDestructuringErrors.parenthesizedBind<0){refDestructuringErrors.parenthesizedBind=start}}return expr;case types.bracketL:node=this.startNode();this.next();node.elements=this.parseExprList(types.bracketR,true,true,refDestructuringErrors);return this.finishNode(node,"ArrayExpression");case types.braceL:return this.parseObj(false,refDestructuringErrors);case types._function:node=this.startNode();this.next();return this.parseFunction(node,0);case types._class:return this.parseClass(this.startNode(),false);case types._new:return this.parseNew();case types.backQuote:return this.parseTemplate();case types._import:if(this.options.ecmaVersion>=11){return this.parseExprImport()}else{return this.unexpected()}default:this.unexpected()}};pp$3.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.parenL:return this.parseDynamicImport(node);case types.dot:node.meta=meta;return this.parseImportMeta(node);default:this.unexpected()}};pp$3.parseDynamicImport=function(node){this.next();node.source=this.parseMaybeAssign();if(!this.eat(types.parenR)){var errorPos=this.start;if(this.eat(types.comma)&&this.eat(types.parenR)){this.raiseRecoverable(errorPos,"Trailing comma is not allowed in import()")}else{this.unexpected(errorPos)}}return this.finishNode(node,"ImportExpression")};pp$3.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.raiseRecoverable(node.start,"Cannot use 'import.meta' outside a module")}return this.finishNode(node,"MetaProperty")};pp$3.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$3.parseParenExpression=function(){this.expect(types.parenL);var val=this.parseExpression();this.expect(types.parenR);return val};pp$3.parseParenAndDistinguishExpression=function(canBeArrow){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.parenR){first?first=false:this.expect(types.comma);if(allowTrailingComma&&this.afterTrailingComma(types.parenR,true)){lastIsComma=true;break}else if(this.type===types.ellipsis){spreadStart=this.start;exprList.push(this.parseParenItem(this.parseRestBinding()));if(this.type===types.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.start,innerEndLoc=this.startLoc;this.expect(types.parenR);if(canBeArrow&&!this.canInsertSemicolon()&&this.eat(types.arrow)){this.checkPatternErrors(refDestructuringErrors,false);this.checkYieldAwaitInDefaultParams();this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;return this.parseParenArrowList(startPos,startLoc,exprList)}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$3.parseParenItem=function(item){return item};pp$3.parseParenArrowList=function(startPos,startLoc,exprList){return this.parseArrowExpression(this.startNodeAt(startPos,startLoc),exprList)};var empty$1=[];pp$3.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.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.inNonArrowFunction){this.raiseRecoverable(node.start,"'new.target' can only be used in functions")}return this.finishNode(node,"MetaProperty")}var startPos=this.start,startLoc=this.startLoc,isImport=this.type===types._import;node.callee=this.parseSubscripts(this.parseExprAtom(),startPos,startLoc,true);if(isImport&&node.callee.type==="ImportExpression"){this.raise(startPos,"Cannot use new with import()")}if(this.eat(types.parenL)){node.arguments=this.parseExprList(types.parenR,this.options.ecmaVersion>=8,false)}else{node.arguments=empty$1}return this.finishNode(node,"NewExpression")};pp$3.parseTemplateElement=function(ref){var isTagged=ref.isTagged;var elem=this.startNode();if(this.type===types.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.backQuote;return this.finishNode(elem,"TemplateElement")};pp$3.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.eof){this.raise(this.pos,"Unterminated template literal")}this.expect(types.dollarBraceL);node.expressions.push(this.parseExpression());this.expect(types.braceR);node.quasis.push(curElt=this.parseTemplateElement({isTagged:isTagged}))}this.next();return this.finishNode(node,"TemplateLiteral")};pp$3.isAsyncProp=function(prop){return!prop.computed&&prop.key.type==="Identifier"&&prop.key.name==="async"&&(this.type===types.name||this.type===types.num||this.type===types.string||this.type===types.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===types.star)&&!lineBreak.test(this.input.slice(this.lastTokEnd,this.start))};pp$3.parseObj=function(isPattern,refDestructuringErrors){var node=this.startNode(),first=true,propHash={};node.properties=[];this.next();while(!this.eat(types.braceR)){if(!first){this.expect(types.comma);if(this.options.ecmaVersion>=5&&this.afterTrailingComma(types.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$3.parseProperty=function(isPattern,refDestructuringErrors){var prop=this.startNode(),isGenerator,isAsync,startPos,startLoc;if(this.options.ecmaVersion>=9&&this.eat(types.ellipsis)){if(isPattern){prop.argument=this.parseIdent(false);if(this.type===types.comma){this.raise(this.start,"Comma is not permitted after the rest element")}return this.finishNode(prop,"RestElement")}if(this.type===types.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.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.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.star);this.parsePropertyName(prop,refDestructuringErrors)}else{isAsync=false}this.parsePropertyValue(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc);return this.finishNode(prop,"Property")};pp$3.parsePropertyValue=function(prop,isPattern,isGenerator,isAsync,startPos,startLoc,refDestructuringErrors,containsEsc){if((isGenerator||isAsync)&&this.type===types.colon){this.unexpected()}if(this.eat(types.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.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.comma&&this.type!==types.braceR&&this.type!==types.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.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$3.parsePropertyName=function(prop){if(this.options.ecmaVersion>=6){if(this.eat(types.bracketL)){prop.computed=true;prop.key=this.parseMaybeAssign();this.expect(types.bracketR);return prop.key}else{prop.computed=false}}return prop.key=this.type===types.num||this.type===types.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!=="never")};pp$3.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$3.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.parenL);node.params=this.parseBindingList(types.parenR,false,this.options.ecmaVersion>=8);this.checkYieldAwaitInDefaultParams();this.parseFunctionBody(node,false,true);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"FunctionExpression")};pp$3.parseArrowExpression=function(node,params,isAsync){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);this.yieldPos=oldYieldPos;this.awaitPos=oldAwaitPos;this.awaitIdentPos=oldAwaitIdentPos;return this.finishNode(node,"ArrowFunctionExpression")};pp$3.parseFunctionBody=function(node,isArrowFunction,isMethod){var isExpression=isArrowFunction&&this.type!==types.braceL;var oldStrict=this.strict,useStrict=false;if(isExpression){node.body=this.parseMaybeAssign();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$3.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$5.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$5.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]};pp$5.currentVarScope=function(){for(var i=this.scopeStack.length-1;;i--){var scope=this.scopeStack[i];if(scope.flags&SCOPE_VAR){return scope}}};pp$5.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$6=Parser.prototype;pp$6.startNode=function(){return new Node(this,this.start,this.startLoc)};pp$6.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$6.finishNode=function(node,type){return finishNodeAt.call(this,node,type,this.lastTokEnd,this.lastTokEndLoc)};pp$6.finishNodeAt=function(node,type,pos,loc){return finishNodeAt.call(this,node,type,pos,loc)};pp$6.copyNode=function(node){var newNode=new Node(this,node.start,this.startLoc);for(var prop in node){newNode[prop]=node[prop]}return newNode};var TokContext=function TokContext(token,isExpr,preserveSpace,override,generator){this.token=token;this.isExpr=!!isExpr;this.preserveSpace=!!preserveSpace;this.override=override;this.generator=!!generator};var types$1={b_stat:new TokContext("{",false),b_expr:new TokContext("{",true),b_tmpl:new TokContext("${",false),p_stat:new TokContext("(",false),p_expr:new TokContext("(",true),q_tmpl:new TokContext("`",true,true,(function(p){return p.tryReadTemplateToken()})),f_stat:new TokContext("function",false),f_expr:new TokContext("function",true),f_expr_gen:new TokContext("function",true,false,null,true),f_gen:new TokContext("function",false,false,null,true)};var pp$7=Parser.prototype;pp$7.initialContext=function(){return[types$1.b_stat]};pp$7.braceIsBlock=function(prevType){var parent=this.curContext();if(parent===types$1.f_expr||parent===types$1.f_stat){return true}if(prevType===types.colon&&(parent===types$1.b_stat||parent===types$1.b_expr)){return!parent.isExpr}if(prevType===types._return||prevType===types.name&&this.exprAllowed){return lineBreak.test(this.input.slice(this.lastTokEnd,this.start))}if(prevType===types._else||prevType===types.semi||prevType===types.eof||prevType===types.parenR||prevType===types.arrow){return true}if(prevType===types.braceL){return parent===types$1.b_stat}if(prevType===types._var||prevType===types._const||prevType===types.name){return false}return!this.exprAllowed};pp$7.inGeneratorContext=function(){for(var i=this.context.length-1;i>=1;i--){var context=this.context[i];if(context.token==="function"){return context.generator}}return false};pp$7.updateContext=function(prevType){var update,type=this.type;if(type.keyword&&prevType===types.dot){this.exprAllowed=false}else if(update=type.updateContext){update.call(this,prevType)}else{this.exprAllowed=type.beforeExpr}};types.parenR.updateContext=types.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=true;return}var out=this.context.pop();if(out===types$1.b_stat&&this.curContext().token==="function"){out=this.context.pop()}this.exprAllowed=!out.isExpr};types.braceL.updateContext=function(prevType){this.context.push(this.braceIsBlock(prevType)?types$1.b_stat:types$1.b_expr);this.exprAllowed=true};types.dollarBraceL.updateContext=function(){this.context.push(types$1.b_tmpl);this.exprAllowed=true};types.parenL.updateContext=function(prevType){var statementParens=prevType===types._if||prevType===types._for||prevType===types._with||prevType===types._while;this.context.push(statementParens?types$1.p_stat:types$1.p_expr);this.exprAllowed=true};types.incDec.updateContext=function(){};types._function.updateContext=types._class.updateContext=function(prevType){if(prevType.beforeExpr&&prevType!==types._else&&!(prevType===types.semi&&this.curContext()!==types$1.p_stat)&&!(prevType===types._return&&lineBreak.test(this.input.slice(this.lastTokEnd,this.start)))&&!((prevType===types.colon||prevType===types.braceL)&&this.curContext()===types$1.b_stat)){this.context.push(types$1.f_expr)}else{this.context.push(types$1.f_stat)}this.exprAllowed=false};types.backQuote.updateContext=function(){if(this.curContext()===types$1.q_tmpl){this.context.pop()}else{this.context.push(types$1.q_tmpl)}this.exprAllowed=false};types.star.updateContext=function(prevType){if(prevType===types._function){var index=this.context.length-1;if(this.context[index]===types$1.f_expr){this.context[index]=types$1.f_expr_gen}else{this.context[index]=types$1.f_gen}}this.exprAllowed=true};types.name.updateContext=function(prevType){var allowed=false;if(this.options.ecmaVersion>=6&&prevType!==types.dot){if(this.value==="of"&&!this.exprAllowed||this.value==="yield"&&this.inGeneratorContext()){allowed=true}}this.exprAllowed=allowed};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 unicodeBinaryProperties={9:ecma9BinaryProperties,10:ecma10BinaryProperties,11:ecma11BinaryProperties,12:ecma12BinaryProperties};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 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 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 unicodeScriptValues={9:ecma9ScriptValues,10:ecma10ScriptValues,11:ecma11ScriptValues,12:ecma12ScriptValues};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}buildUnicodeData(9);buildUnicodeData(10);buildUnicodeData(11);buildUnicodeData(12);var pp$8=Parser.prototype;var RegExpValidationState=function RegExpValidationState(parser){this.parser=parser;this.validFlags="gim"+(parser.options.ecmaVersion>=6?"uy":"")+(parser.options.ecmaVersion>=9?"s":"");this.unicodeProperties=data[parser.options.ecmaVersion>=12?12: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(ch){if(ch<=65535){return String.fromCharCode(ch)}ch-=65536;return String.fromCharCode((ch>>10)+55296,(ch&1023)+56320)}pp$8.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$8.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$8.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$8.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$8.regexp_eatQuantifierPrefix=function(state,noError){return state.eat(42)||state.eat(43)||state.eat(63)||this.regexp_eatBracedQuantifier(state,noError)};pp$8.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$8.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$8.regexp_eatInvalidBracedQuantifier=function(state){if(this.regexp_eatBracedQuantifier(state,true)){state.raise("Nothing to repeat")}return false};pp$8.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$8.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$8.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$8.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$8.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$8.regexp_eatRegExpIdentifierName=function(state){state.lastStringValue="";if(this.regexp_eatRegExpIdentifierStart(state)){state.lastStringValue+=codePointToString(state.lastIntValue);while(this.regexp_eatRegExpIdentifierPart(state)){state.lastStringValue+=codePointToString(state.lastIntValue)}return true}return false};pp$8.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$8.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$8.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$8.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$8.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$8.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$8.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$8.regexp_eatZero=function(state){if(state.current()===48&&!isDecimalDigit(state.lookahead())){state.lastIntValue=0;state.advance();return true}return false};pp$8.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$8.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$8.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$8.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$8.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$8.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$8.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$8.regexp_validateUnicodePropertyNameAndValue=function(state,name,value){if(!has(state.unicodeProperties.nonBinary,name)){state.raise("Invalid property name")}if(!state.unicodeProperties.nonBinary[name].test(value)){state.raise("Invalid property value")}};pp$8.regexp_validateUnicodePropertyNameOrValue=function(state,nameOrValue){if(!state.unicodeProperties.binary.test(nameOrValue)){state.raise("Invalid property name")}};pp$8.regexp_eatUnicodePropertyName=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyNameCharacter(ch=state.current())){state.lastStringValue+=codePointToString(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyNameCharacter(ch){return isControlLetter(ch)||ch===95}pp$8.regexp_eatUnicodePropertyValue=function(state){var ch=0;state.lastStringValue="";while(isUnicodePropertyValueCharacter(ch=state.current())){state.lastStringValue+=codePointToString(ch);state.advance()}return state.lastStringValue!==""};function isUnicodePropertyValueCharacter(ch){return isUnicodePropertyNameCharacter(ch)||isDecimalDigit(ch)}pp$8.regexp_eatLoneUnicodePropertyNameOrValue=function(state){return this.regexp_eatUnicodePropertyValue(state)};pp$8.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$8.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$8.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$8.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$8.regexp_eatClassControlLetter=function(state){var ch=state.current();if(isDecimalDigit(ch)||ch===95){state.lastIntValue=ch%32;state.advance();return true}return false};pp$8.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$8.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$8.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$8.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$8.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$8.regexp_eatFixedHexDigits=function(state,length){var start=state.pos;state.lastIntValue=0;for(var i=0;i=this.input.length){return this.finishToken(types.eof)}if(curContext.override){return curContext.override(this)}else{this.readToken(this.fullCharCodeAtPos())}};pp$9.readToken=function(code){if(isIdentifierStart(code,this.options.ecmaVersion>=6)||code===92){return this.readWord()}return this.getTokenFromCode(code)};pp$9.fullCharCodeAtPos=function(){var code=this.input.charCodeAt(this.pos);if(code<=55295||code>=57344){return code}var next=this.input.charCodeAt(this.pos+1);return(code<<10)+next-56613888};pp$9.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){lineBreakG.lastIndex=start;var match;while((match=lineBreakG.exec(this.input))&&match.index8&&ch<14||ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++this.pos}else{break loop}}}};pp$9.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$9.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.ellipsis)}else{++this.pos;return this.finishToken(types.dot)}};pp$9.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.assign,2)}return this.finishOp(types.slash,1)};pp$9.readToken_mult_modulo_exp=function(code){var next=this.input.charCodeAt(this.pos+1);var size=1;var tokentype=code===42?types.star:types.modulo;if(this.options.ecmaVersion>=7&&code===42&&next===42){++size;tokentype=types.starstar;next=this.input.charCodeAt(this.pos+2)}if(next===61){return this.finishOp(types.assign,size+1)}return this.finishOp(tokentype,size)};pp$9.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.assign,3)}}return this.finishOp(code===124?types.logicalOR:types.logicalAND,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(code===124?types.bitwiseOR:types.bitwiseAND,1)};pp$9.readToken_caret=function(){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.bitwiseXOR,1)};pp$9.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.incDec,2)}if(next===61){return this.finishOp(types.assign,2)}return this.finishOp(types.plusMin,1)};pp$9.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.assign,size+1)}return this.finishOp(types.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.relational,size)};pp$9.readToken_eq_excl=function(code){var next=this.input.charCodeAt(this.pos+1);if(next===61){return this.finishOp(types.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.arrow)}return this.finishOp(code===61?types.eq:types.prefix,1)};pp$9.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.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.assign,3)}}return this.finishOp(types.coalesce,2)}}return this.finishOp(types.question,1)};pp$9.getTokenFromCode=function(code){switch(code){case 46:return this.readToken_dot();case 40:++this.pos;return this.finishToken(types.parenL);case 41:++this.pos;return this.finishToken(types.parenR);case 59:++this.pos;return this.finishToken(types.semi);case 44:++this.pos;return this.finishToken(types.comma);case 91:++this.pos;return this.finishToken(types.bracketL);case 93:++this.pos;return this.finishToken(types.bracketR);case 123:++this.pos;return this.finishToken(types.braceL);case 125:++this.pos;return this.finishToken(types.braceR);case 58:++this.pos;return this.finishToken(types.colon);case 96:if(this.options.ecmaVersion<6){break}++this.pos;return this.finishToken(types.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.prefix,1)}this.raise(this.pos,"Unexpected character '"+codePointToString$1(code)+"'")};pp$9.finishOp=function(type,size){var str=this.input.slice(this.pos,this.pos+size);this.pos+=size;return this.finishToken(type,str)};pp$9.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.regexp,{pattern:pattern,flags:flags,value:value})};pp$9.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$9.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.num,val)};pp$9.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.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.num,val)};pp$9.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$1(code){if(code<=65535){return String.fromCharCode(code)}code-=65536;return String.fromCharCode((code>>10)+55296,(code&1023)+56320)}pp$9.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(isNewLine(ch,this.options.ecmaVersion>=10)){this.raise(this.start,"Unterminated string constant")}++this.pos}}out+=this.input.slice(chunkStart,this.pos++);return this.finishToken(types.string,out)};var INVALID_TEMPLATE_ESCAPE_ERROR={};pp$9.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$9.invalidStringToken=function(position,message){if(this.inTemplateElement&&this.options.ecmaVersion>=9){throw INVALID_TEMPLATE_ESCAPE_ERROR}else{this.raise(position,message)}};pp$9.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.template||this.type===types.invalidTemplate)){if(ch===36){this.pos+=2;return this.finishToken(types.dollarBraceL)}else{++this.pos;return this.finishToken(types.backQuote)}}out+=this.input.slice(chunkStart,this.pos);return this.finishToken(types.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$9.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$9.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$9.readWord1=function(){this.containsEsc=false;var word="",first=true,chunkStart=this.pos;var astral=this.options.ecmaVersion>=6;while(this.posbytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i0&&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;var EXPRESSIONS_PRECEDENCE={ArrayExpression:20,TaggedTemplateExpression:20,ThisExpression:20,Identifier:20,Literal:18,TemplateLiteral:20,Super:20,SequenceExpression:20,MemberExpression:19,CallExpression:19,NewExpression:19,ArrowFunctionExpression:NEEDS_PARENTHESES,ClassExpression:NEEDS_PARENTHESES,FunctionExpression:NEEDS_PARENTHESES,ObjectExpression:NEEDS_PARENTHESES,UpdateExpression:16,UnaryExpression:15,BinaryExpression:14,LogicalExpression:13,ConditionalExpression:4,AssignmentExpression:3,AwaitExpression:2,YieldExpression:2,RestElement:1};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 ");if(node.argument){this[node.argument.type](node.argument,state)}},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){state.write(" ")}if(EXPRESSIONS_PRECEDENCE[node.argument.type]EXPRESSIONS_PRECEDENCE.ConditionalExpression){this[node.test.type](node.test,state)}else{state.write("(");this[node.test.type](node.test,state);state.write(")")}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 ");if(EXPRESSIONS_PRECEDENCE[node.callee.type]0){if(this.lineEndSize>0){if(code.endsWith(this.lineEnd)){this.line+=this.lineEndSize;this.column=0}else if(code[code.length-1]==="\n"){this.line++;this.column=0}else{this.column+=code.length}}else{if(code[code.length-1]==="\n"){this.line++;this.column=0}else{this.column+=code.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}},{}],21:[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}},{}],22:[function(require,module,exports){(function(chars){"use strict";exports.encode=function(arraybuffer){var bytes=new Uint8Array(arraybuffer),i,len=bytes.length,base64="";for(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};exports.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}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],23:[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("")}},{}],24:[function(require,module,exports){var BlobBuilder=typeof BlobBuilder!=="undefined"?BlobBuilder:typeof WebKitBlobBuilder!=="undefined"?WebKitBlobBuilder:typeof MSBlobBuilder!=="undefined"?MSBlobBuilder:typeof MozBlobBuilder!=="undefined"?MozBlobBuilder:false;var blobSupported=function(){try{var a=new Blob(["hi"]);return a.size===2}catch(e){return false}}();var blobSupportsArrayBufferView=blobSupported&&function(){try{var b=new Blob([new Uint8Array([1,2])]);return b.size===2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function mapArrayBufferViews(ary){return ary.map((function(chunk){if(chunk.buffer instanceof ArrayBuffer){var buf=chunk.buffer;if(chunk.byteLength!==buf.byteLength){var copy=new Uint8Array(chunk.byteLength);copy.set(new Uint8Array(buf,chunk.byteOffset,chunk.byteLength));buf=copy.buffer}return buf}return chunk}))}function BlobBuilderConstructor(ary,options){options=options||{};var bb=new BlobBuilder;mapArrayBufferViews(ary).forEach((function(part){bb.append(part)}));return options.type?bb.getBlob(options.type):bb.getBlob()}function BlobConstructor(ary,options){return new Blob(mapArrayBufferViews(ary),options||{})}if(typeof Blob!=="undefined"){BlobBuilderConstructor.prototype=Blob.prototype;BlobConstructor.prototype=Blob.prototype}module.exports=function(){if(blobSupported){return blobSupportsArrayBufferView?Blob:BlobConstructor}else if(blobBuilderSupported){return BlobBuilderConstructor}else{return undefined}}()},{}],25:[function(require,module,exports){},{}],26:[function(require,module,exports){var objectCreate=Object.create||objectCreatePolyfill;var objectKeys=Object.keys||objectKeysPolyfill;var bind=Function.prototype.bind||functionBindPolyfill;function EventEmitter(){if(!this._events||!Object.prototype.hasOwnProperty.call(this,"_events")){this._events=objectCreate(null);this._eventsCount=0}this._maxListeners=this._maxListeners||undefined}module.exports=EventEmitter;EventEmitter.EventEmitter=EventEmitter;EventEmitter.prototype._events=undefined;EventEmitter.prototype._maxListeners=undefined;var defaultMaxListeners=10;var hasDefineProperty;try{var o={};if(Object.defineProperty)Object.defineProperty(o,"x",{value:0});hasDefineProperty=o.x===0}catch(err){hasDefineProperty=false}if(hasDefineProperty){Object.defineProperty(EventEmitter,"defaultMaxListeners",{enumerable:true,get:function(){return defaultMaxListeners},set:function(arg){if(typeof arg!=="number"||arg<0||arg!==arg)throw new TypeError('"defaultMaxListeners" must be a positive number');defaultMaxListeners=arg}})}else{EventEmitter.defaultMaxListeners=defaultMaxListeners}EventEmitter.prototype.setMaxListeners=function setMaxListeners(n){if(typeof n!=="number"||n<0||isNaN(n))throw new TypeError('"n" argument must be a positive number');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)};function emitNone(handler,isFn,self){if(isFn)handler.call(self);else{var len=handler.length;var listeners=arrayClone(handler,len);for(var i=0;i1)er=arguments[1];if(er instanceof Error){throw er}else{var err=new Error('Unhandled "error" event. ('+er+")");err.context=er;throw err}return false}handler=events[type];if(!handler)return false;var isFn=typeof handler==="function";len=arguments.length;switch(len){case 1:emitNone(handler,isFn,this);break;case 2:emitOne(handler,isFn,this,arguments[1]);break;case 3:emitTwo(handler,isFn,this,arguments[1],arguments[2]);break;case 4:emitThree(handler,isFn,this,arguments[1],arguments[2],arguments[3]);break;default:args=new Array(len-1);for(i=1;i0&&existing.length>m){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;if(typeof console==="object"&&console.warn){console.warn("%s: %s",w.name,w.message)}}}}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;switch(arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:var args=new Array(arguments.length);for(var i=0;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)this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter.prototype.removeAllListeners=function removeAllListeners(type){var listeners,events,i;events=this._events;if(!events)return this;if(!events.removeListener){if(arguments.length===0){this._events=objectCreate(null);this._eventsCount=0}else if(events[type]){if(--this._eventsCount===0)this._events=objectCreate(null);else delete events[type]}return this}if(arguments.length===0){var keys=objectKeys(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)return[];var evlistener=events[type];if(!evlistener)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){var evlistener=events[type];if(typeof evlistener==="function"){return 1}else if(evlistener){return evlistener.length}}return 0}EventEmitter.prototype.eventNames=function eventNames(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};function spliceOne(list,index){for(var i=index,k=i+1,n=list.length;k * @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":23,buffer:27,ieee754:78}],28:[function(require,module,exports){(function(r){"object"==typeof exports&&"object"==typeof module?r(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],r):r(CodeMirror)})((function(r){function I(c){c=c.search(w);return-1==c?0:c}function J(c,d,a){return/\bstring\b/.test(c.getTokenTypeAt(l(d.line,0)))&&!/^['"`]/.test(a)}function G(c,d){var a=c.getMode();return!1!==a.useInnerComments&&a.innerMode?c.getModeAt(d):a}var E={},w=/[^\s\u00a0]/,l=r.Pos,K=r.cmpPos;r.commands.toggleComment=function(c){c.toggleComment()};r.defineExtension("toggleComment",(function(c){c||(c=E);for(var d=Infinity,a=this.listSelections(),b=null,e=a.length-1;0<=e;e--){var g=a[e].from(),f=a[e].to();g.line>=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":32}],30:[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":32}],31:[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 ve(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=we(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,ue(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 Ae(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=Ce(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 Ge(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 He(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 Ie(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 Je(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=ye(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=Ie(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 Ke(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 Le(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 Ne(a,b){var d=a.display.externalMeasured;return d&&d.line==b.line?(a.display.externalMeasured=null,b.measure=d.measure,d.built):Je(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 Oe(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=Ue;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}:Ue);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 $e(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 af(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 bf(a,b,d,c){d||(d=cb(a,b));c=Gc(a,b,ya(a,d,c),"line").top;return af(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=qe(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=af(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 df(a){a=a.display.view;for(var b=0,d=0;d=a.display.viewTo||h.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=bf(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,Nd=0==L;L=!S||L==S.length-1;3>=ta.top-na.top?(R=(n?fb:gb)&&Nd?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&&Nd?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&&Nd?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=Re(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||Pd(a))}function Qd(a){a.state.delayingBlurEvent=!0;setTimeout((function(){a.state.delayingBlurEvent&&(a.state.delayingBlurEvent=!1,a.state.focused&&ub(a))}),100)}function Pd(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()),Od(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 Rd(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=$e(a,b.from),c=$e(a,b.to);jf(a,d,c,b.margin)}}function jf(a,b,d,c){b=Rd(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||Sd(a,{top:b}),kf(a,b,!0),La&&Sd(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=Rd(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=we(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==df(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=He(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=df(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(!Td(a,b))break;Kc(a);c=Xb(a);Tb(a);wb(a,c);Ud(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 Sd(a,b){b=new Oc(a,b);if(Td(a,b)){Kc(a);pf(a,b);var d=Xb(a);Tb(a);wb(a,d);Ud(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=Wd(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),Sd(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 Xd(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([ae(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,re(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=Xd(a,b));a.cm?$g(a.cm,b,c):Zd(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 ce(a,b,d){b=qe(a.text,b+d,d);return 0>b||b>a.text.length?null:b}function de(a,b,d){a=ce(a,b.ch,d);return null==a?null:new t(b.line,a,0>d?"after":"before")}function ee(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=ce(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 de(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&&(fe=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==fe)fe=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 ge(d,a,b),kc=null,"double";kc=new ge(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=te(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(he)this.display.input.onContextMenu(a);else Qd(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:Qd(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&&Qd(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")&&!he)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&&Pd(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();ff(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 Pd(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=le(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 ke(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):de(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=ee(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=Se(d,c,b.line);a=Ia(c,a.doc.direction);c="left";a&&(c=Ib(a,b.ch)%2?"right":"left");b=Te(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)),he=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,le=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.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 je=[];U.defineInitHook=function(a){return je.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=ef(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(he){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;Yd(c)}),!0);b("indentUnit",2,Yd,!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=Wd(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=Wd(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=Rd(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=me(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=le;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=ue;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=se;a.e_stop=Kb;a.addClass=Wa;a.contains=ja;a.rmClass=hb;a.keyNames=Ua})(U);U.version="5.63.3";return U}))}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],33:[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":32}],34:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],35:[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;i0){this.extraHeaders=opts.extraHeaders}if(opts.localAddress){this.localAddress=opts.localAddress}}this.id=null;this.upgrades=null;this.pingInterval=null;this.pingTimeout=null;this.pingIntervalTimer=null;this.pingTimeoutTimer=null;this.open()}Socket.priorWebsocketSuccess=false;Emitter(Socket.prototype);Socket.protocol=parser.protocol;Socket.Socket=Socket;Socket.Transport=require("./transport");Socket.transports=require("./transports/index");Socket.parser=require("engine.io-parser");Socket.prototype.createTransport=function(name){debug('creating transport "%s"',name);var query=clone(this.query);query.EIO=parser.protocol;query.transport=name;var options=this.transportOptions[name]||{};if(this.id)query.sid=this.id;var transport=new transports[name]({query:query,socket:this,agent:options.agent||this.agent,hostname:options.hostname||this.hostname,port:options.port||this.port,secure:options.secure||this.secure,path:options.path||this.path,forceJSONP:options.forceJSONP||this.forceJSONP,jsonp:options.jsonp||this.jsonp,forceBase64:options.forceBase64||this.forceBase64,enablesXDR:options.enablesXDR||this.enablesXDR,withCredentials:options.withCredentials||this.withCredentials,timestampRequests:options.timestampRequests||this.timestampRequests,timestampParam:options.timestampParam||this.timestampParam,policyPort:options.policyPort||this.policyPort,pfx:options.pfx||this.pfx,key:options.key||this.key,passphrase:options.passphrase||this.passphrase,cert:options.cert||this.cert,ca:options.ca||this.ca,ciphers:options.ciphers||this.ciphers,rejectUnauthorized:options.rejectUnauthorized||this.rejectUnauthorized,perMessageDeflate:options.perMessageDeflate||this.perMessageDeflate,extraHeaders:options.extraHeaders||this.extraHeaders,forceNode:options.forceNode||this.forceNode,localAddress:options.localAddress||this.localAddress,requestTimeout:options.requestTimeout||this.requestTimeout,protocols:options.protocols||void 0,isReactNative:this.isReactNative});return transport};function clone(obj){var o={};for(var i in obj){if(obj.hasOwnProperty(i)){o[i]=obj[i]}}return o}Socket.prototype.open=function(){var transport;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1){transport="websocket"}else if(0===this.transports.length){var self=this;setTimeout((function(){self.emit("error","No transports available")}),0);return}else{transport=this.transports[0]}this.readyState="opening";try{transport=this.createTransport(transport)}catch(e){this.transports.shift();this.open();return}transport.open();this.setTransport(transport)};Socket.prototype.setTransport=function(transport){debug("setting transport %s",transport.name);var self=this;if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",(function(){self.onDrain()})).on("packet",(function(packet){self.onPacket(packet)})).on("error",(function(e){self.onError(e)})).on("close",(function(){self.onClose("transport close")}))};Socket.prototype.probe=function(name){debug('probing transport "%s"',name);var transport=this.createTransport(name,{probe:1});var failed=false;var self=this;Socket.priorWebsocketSuccess=false;function onTransportOpen(){if(self.onlyBinaryUpgrades){var upgradeLosesBinary=!this.supportsBinary&&self.transport.supportsBinary;failed=failed||upgradeLosesBinary}if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",(function(msg){if(failed)return;if("pong"===msg.type&&"probe"===msg.data){debug('probe transport "%s" pong',name);self.upgrading=true;self.emit("upgrading",transport);if(!transport)return;Socket.priorWebsocketSuccess="websocket"===transport.name;debug('pausing current transport "%s"',self.transport.name);self.transport.pause((function(){if(failed)return;if("closed"===self.readyState)return;debug("changing transport and sending upgrade packet");cleanup();self.setTransport(transport);transport.send([{type:"upgrade"}]);self.emit("upgrade",transport);transport=null;self.upgrading=false;self.flush()}))}else{debug('probe transport "%s" failed',name);var err=new Error("probe error");err.transport=transport.name;self.emit("upgradeError",err)}}))}function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}function onerror(err){var error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);self.emit("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()}}function cleanup(){transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);self.removeListener("close",onclose);self.removeListener("upgrading",onupgrade)}transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()};Socket.prototype.onOpen=function(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"===this.transport.name;this.emit("open");this.flush();if("open"===this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var i=0,l=this.upgrades.length;i';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState==="complete"){complete()}}}else{this.iframe.onload=complete}}},{"../globalThis":38,"./polling":45,"component-inherit":36}],44:[function(require,module,exports){var XMLHttpRequest=require("xmlhttprequest-ssl");var Polling=require("./polling");var Emitter=require("component-emitter");var inherit=require("component-inherit");var debug=require("debug")("engine.io-client:polling-xhr");var globalThis=require("../globalThis");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);this.requestTimeout=opts.requestTimeout;this.extraHeaders=opts.extraHeaders;if(typeof location!=="undefined"){var isSSL="https:"===location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=typeof location!=="undefined"&&opts.hostname!==location.hostname||port!==opts.port;this.xs=opts.secure!==isSSL}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.xs=this.xs;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;opts.enablesXDR=this.enablesXDR;opts.withCredentials=this.withCredentials;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;opts.requestTimeout=this.requestTimeout;opts.extraHeaders=this.extraHeaders;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",(function(err){self.onError("xhr post error",err)}));this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",(function(data){self.onData(data)}));req.on("error",(function(err){self.onError("xhr poll error",err)}));this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.xs=!!opts.xs;this.async=false!==opts.async;this.data=undefined!==opts.data?opts.data:null;this.agent=opts.agent;this.isBinary=opts.isBinary;this.supportsBinary=opts.supportsBinary;this.enablesXDR=opts.enablesXDR;this.withCredentials=opts.withCredentials;this.requestTimeout=opts.requestTimeout;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.extraHeaders=opts.extraHeaders;this.create()}Emitter(Request.prototype);Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts);var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);try{if(this.extraHeaders){xhr.setDisableHeaderCheck&&xhr.setDisableHeaderCheck(true);for(var i in this.extraHeaders){if(this.extraHeaders.hasOwnProperty(i)){xhr.setRequestHeader(i,this.extraHeaders[i])}}}}catch(e){}if("POST"===this.method){try{if(this.isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}try{xhr.setRequestHeader("Accept","*/*")}catch(e){}if("withCredentials"in xhr){xhr.withCredentials=this.withCredentials}if(this.requestTimeout){xhr.timeout=this.requestTimeout}if(this.hasXDR()){xhr.onload=function(){self.onLoad()};xhr.onerror=function(){self.onError(xhr.responseText)}}else{xhr.onreadystatechange=function(){if(xhr.readyState===2){try{var contentType=xhr.getResponseHeader("Content-Type");if(self.supportsBinary&&contentType==="application/octet-stream"||contentType==="application/octet-stream; charset=UTF-8"){xhr.responseType="arraybuffer"}}catch(e){}}if(4!==xhr.readyState)return;if(200===xhr.status||1223===xhr.status){self.onLoad()}else{setTimeout((function(){self.onError(typeof xhr.status==="number"?xhr.status:0)}),0)}}}debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout((function(){self.onError(e)}),0);return}if(typeof document!=="undefined"){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup(true)};Request.prototype.cleanup=function(fromError){if("undefined"===typeof this.xhr||null===this.xhr){return}if(this.hasXDR()){this.xhr.onload=this.xhr.onerror=empty}else{this.xhr.onreadystatechange=empty}if(fromError){try{this.xhr.abort()}catch(e){}}if(typeof document!=="undefined"){delete Request.requests[this.index]}this.xhr=null};Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type")}catch(e){}if(contentType==="application/octet-stream"||contentType==="application/octet-stream; charset=UTF-8"){data=this.xhr.response||this.xhr.responseText}else{data=this.xhr.responseText}}catch(e){this.onError(e)}if(null!=data){this.onData(data)}};Request.prototype.hasXDR=function(){return typeof XDomainRequest!=="undefined"&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};Request.requestsCount=0;Request.requests={};if(typeof document!=="undefined"){if(typeof attachEvent==="function"){attachEvent("onunload",unloadHandler)}else if(typeof addEventListener==="function"){var terminationEvent="onpagehide"in globalThis?"pagehide":"unload";addEventListener(terminationEvent,unloadHandler,false)}}function unloadHandler(){for(var i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}},{"../globalThis":38,"./polling":45,"component-emitter":48,"component-inherit":36,debug:49,"xmlhttprequest-ssl":47}],45:[function(require,module,exports){var Transport=require("../transport");var parseqs=require("parseqs");var parser=require("engine.io-parser");var inherit=require("component-inherit");var yeast=require("yeast");var debug=require("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){var XMLHttpRequest=require("xmlhttprequest-ssl");var xhr=new XMLHttpRequest({xdomain:false});return null!=xhr.responseType}();function Polling(opts){var forceBase64=opts&&opts.forceBase64;if(!hasXHR2||forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(Polling,Transport);Polling.prototype.name="polling";Polling.prototype.doOpen=function(){this.poll()};Polling.prototype.pause=function(onPause){var self=this;this.readyState="pausing";function pause(){debug("paused");self.readyState="paused";onPause()}if(this.polling||!this.writable){var 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()}};Polling.prototype.poll=function(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")};Polling.prototype.onData=function(data){var self=this;debug("polling got data %s",data);var callback=function(packet,index,total){if("opening"===self.readyState&&packet.type==="open"){self.onOpen()}if("close"===packet.type){self.onClose();return false}self.onPacket(packet)};parser.decodePayload(data,this.socket.binaryType,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)}}};Polling.prototype.doClose=function(){var self=this;function close(){debug("writing close packet");self.write([{type:"close"}])}if("open"===this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}};Polling.prototype.write=function(packets){var self=this;this.writable=false;var callbackfn=function(){self.writable=true;self.emit("drain")};parser.encodePayload(packets,this.supportsBinary,(function(data){self.doWrite(data,callbackfn)}))};Polling.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"https":"http";var port="";if(false!==this.timestampRequests){query[this.timestampParam]=yeast()}if(!this.supportsBinary&&!query.sid){query.b64=1}query=parseqs.encode(query);if(this.port&&("https"===schema&&Number(this.port)!==443||"http"===schema&&Number(this.port)!==80)){port=":"+this.port}if(query.length){query="?"+query}var ipv6=this.hostname.indexOf(":")!==-1;return schema+"://"+(ipv6?"["+this.hostname+"]":this.hostname)+port+this.path+query}},{"../transport":41,"component-inherit":36,debug:49,"engine.io-parser":52,parseqs:108,"xmlhttprequest-ssl":47,yeast:165}],46:[function(require,module,exports){(function(Buffer){(function(){var Transport=require("../transport");var parser=require("engine.io-parser");var parseqs=require("parseqs");var inherit=require("component-inherit");var yeast=require("yeast");var debug=require("debug")("engine.io-client:websocket");var BrowserWebSocket,NodeWebSocket;if(typeof WebSocket!=="undefined"){BrowserWebSocket=WebSocket}else if(typeof self!=="undefined"){BrowserWebSocket=self.WebSocket||self.MozWebSocket}if(typeof window==="undefined"){try{NodeWebSocket=require("ws")}catch(e){}}var WebSocketImpl=BrowserWebSocket||NodeWebSocket;module.exports=WS;function WS(opts){var forceBase64=opts&&opts.forceBase64;if(forceBase64){this.supportsBinary=false}this.perMessageDeflate=opts.perMessageDeflate;this.usingBrowserWebSocket=BrowserWebSocket&&!opts.forceNode;this.protocols=opts.protocols;if(!this.usingBrowserWebSocket){WebSocketImpl=NodeWebSocket}Transport.call(this,opts)}inherit(WS,Transport);WS.prototype.name="websocket";WS.prototype.supportsBinary=true;WS.prototype.doOpen=function(){if(!this.check()){return}var uri=this.uri();var protocols=this.protocols;var opts={};if(!this.isReactNative){opts.agent=this.agent;opts.perMessageDeflate=this.perMessageDeflate;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized}if(this.extraHeaders){opts.headers=this.extraHeaders}if(this.localAddress){opts.localAddress=this.localAddress}try{this.ws=this.usingBrowserWebSocket&&!this.isReactNative?protocols?new WebSocketImpl(uri,protocols):new WebSocketImpl(uri):new WebSocketImpl(uri,protocols,opts)}catch(err){return this.emit("error",err)}if(this.ws.binaryType===undefined){this.supportsBinary=false}if(this.ws.supports&&this.ws.supports.binary){this.supportsBinary=true;this.ws.binaryType="nodebuffer"}else{this.ws.binaryType="arraybuffer"}this.addEventListeners()};WS.prototype.addEventListeners=function(){var self=this;this.ws.onopen=function(){self.onOpen()};this.ws.onclose=function(){self.onClose()};this.ws.onmessage=function(ev){self.onData(ev.data)};this.ws.onerror=function(e){self.onError("websocket error",e)}};WS.prototype.write=function(packets){var self=this;this.writable=false;var total=packets.length;for(var i=0,l=total;i=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return;var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0;var lastC=0;args[0].replace(/%[a-zA-Z%]/g,(function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}}));args.splice(lastC,0,c)}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}}).call(this)}).call(this,require("_process"))},{"./debug":50,_process:112}],50:[function(require,module,exports){exports=module.exports=createDebug.debug=createDebug["default"]=createDebug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require("ms");exports.instances=[];exports.names=[];exports.skips=[];exports.formatters={};function selectColor(namespace){var hash=0,i;for(i in namespace){hash=(hash<<5)-hash+namespace.charCodeAt(i);hash|=0}return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){var prevTime;function debug(){if(!debug.enabled)return;var self=debug;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;var args=new Array(arguments.length);for(var i=0;i0){return parse(val)}else if(type==="number"&&isNaN(val)===false){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|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"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){if(ms>=d){return Math.round(ms/d)+"d"}if(ms>=h){return Math.round(ms/h)+"h"}if(ms>=m){return Math.round(ms/m)+"m"}if(ms>=s){return Math.round(ms/s)+"s"}return ms+"ms"}function fmtLong(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};function tryDecode(data){try{data=utf8.decode(data,{strict:false})}catch(e){return false}return data}exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!base64encoder){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary==="function"){callback=supportsBinary;supportsBinary=null}var isBinary=hasBinary(packets);if(supportsBinary&&isBinary){if(Blob&&!dontSendBlobs){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,!isBinary?false:supportsBinary,false,(function(message){doneCallback(null,setLengthHeader(message))}))}map(packets,encodeOne,(function(err,results){return callback(results.join(""))}))};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,(function(error,msg){result[i]=msg;cb(error,result)}))};for(var i=0;i0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]===255)break;if(msgLength.length>310){return callback(err,0,1)}msgLength+=tailArray[i]}bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;i=55296&&value<=56319&&counter65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function checkScalarValue(codePoint,strict){if(codePoint>=55296&&codePoint<=57343){if(strict){throw Error("Lone surrogate U+"+codePoint.toString(16).toUpperCase()+" is not a scalar value")}return false}return true}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint,strict){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){if(!checkScalarValue(codePoint,strict)){codePoint=65533}symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string,opts){opts=opts||{};var strict=false!==opts.strict;var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(strict){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){return checkScalarValue(codePoint,strict)?codePoint:65533}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&7)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString,opts){opts=opts||{};var strict=false!==opts.strict;byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol(strict))!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}module.exports={version:"2.1.2",encode:utf8encode,decode:utf8decode}},{}],55:[function(require,module,exports){module.exports=function getBrowserRTC(){if(typeof window==="undefined")return null;var wrtc={RTCPeerConnection:window.RTCPeerConnection||window.mozRTCPeerConnection||window.webkitRTCPeerConnection,RTCSessionDescription:window.RTCSessionDescription||window.mozRTCSessionDescription||window.webkitRTCSessionDescription,RTCIceCandidate:window.RTCIceCandidate||window.mozRTCIceCandidate||window.webkitRTCIceCandidate};if(!wrtc.RTCPeerConnection)return null;return wrtc}},{}],56:[function(require,module,exports){(function(Buffer){(function(){var isArray=require("isarray");var toString=Object.prototype.toString;var withNativeBlob=typeof Blob==="function"||typeof Blob!=="undefined"&&toString.call(Blob)==="[object BlobConstructor]";var withNativeFile=typeof File==="function"||typeof File!=="undefined"&&toString.call(File)==="[object FileConstructor]";module.exports=hasBinary;function hasBinary(obj){if(!obj||typeof obj!=="object"){return false}if(isArray(obj)){for(var i=0,l=obj.length;i{},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(1,1,1,0).out(output)}))}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.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":68,"./lib/sandbox.js":73}],62:[function(require,module,exports){const GlslSource=require("./glsl-source.js");class GeneratorFactory{constructor({defaultUniforms:defaultUniforms,defaultOutput:defaultOutput,extendTransforms:extendTransforms=[],changeListener:changeListener=(()=>{})}={}){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){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:this});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});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":63,"./glsl/glsl-functions.js":65}],63:[function(require,module,exports){const generateGlsl=require("./glsl-utils.js").generateGlsl;const formatArguments=require("./glsl-utils.js").formatArguments;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);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},{"./glsl-utils.js":64,"./glsl/utility-functions.js":66}],64:[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]]}}};module.exports={generateGlsl: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},formatArguments:formatArguments};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{val=val.toString();if(val.indexOf(".")<0){val+="."}return val};function formatArguments(transform,startIndex){const defaultArgs=transform.transform.inputs;const userArgs=transform.userArgs;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"){if(typedArg.vecLen>0){typedArg.value=(context,props,batchId)=>fillArrayWithDefaults(userArgs[index](props),typedArg.vecLen)}else{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){if(typedArg.vecLen>0){typedArg.isUniform=true;typedArg.value=fillArrayWithDefaults(typedArg.value,typedArg.vecLen)}else{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":68}],65:[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), _c0.a+_c1.a);`},{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);`},{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);`}]},{}],66:[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 }`}}},{}],67:[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){if(opts.src){this.src=opts.src;this.tex=this.regl.texture(this.src)}if(opts.dynamic)this.dynamic=opts.dynamic}initCam(index){const self=this;Webcam(index).then((response=>{self.src=response.video;self.dynamic=true;self.tex=self.regl.texture(self.src)})).catch((err=>console.log("could not get camera",err)))}initVideo(url=""){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(this.src);this.dynamic=true}));vid.src=url}initImage(url=""){const img=document.createElement("img");img.crossOrigin="anonymous";img.src=url;img.onload=()=>{this.src=img;this.dynamic=false;this.tex=this.regl.texture(this.src)}}initStream(streamName){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(self.src)}}))}}initScreen(){const self=this;Screen().then((function(response){self.src=response.video;self.tex=self.regl.texture(self.src);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":74,"./lib/webcam.js":76}],68:[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":70}],69:[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;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:107}],70:[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}}},{}],71:[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}}}},{}],74:[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)))}))}},{}],75:[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},{}],76:[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))}},{}],77:[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},{}],78:[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}},{}],79:[function(require,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i * @license MIT */ module.exports=function(obj){return obj!=null&&(isBuffer(obj)||isSlowBuffer(obj)||!!obj._isBuffer)};function isBuffer(obj){return!!obj.constructor&&typeof obj.constructor.isBuffer==="function"&&obj.constructor.isBuffer(obj)}function isSlowBuffer(obj){return typeof obj.readFloatLE==="function"&&typeof obj.slice==="function"&&isBuffer(obj.slice(0,0))}},{}],82:[function(require,module,exports){arguments[4][57][0].apply(exports,arguments)},{dup:57}],83:[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":101}],84:[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},{}],85:[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},{}],86:[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},{}],87:[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},{}],88:[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},{}],89:[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":88}],90:[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},{}],91:[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":85,"../core/token":90,"../core/tokenstream":92,"./whitespacepattern":93}],92:[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":84,"../core/inputscanner":85,"../core/output":87,"./options":96}],95:[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":94,"./options":96}],96:[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":87,"../html/options":99,"../html/tokenizer":100}],98:[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":97,"./options":99}],99:[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":86}],100:[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":84,"../core/pattern":88,"../core/templatablepattern":89,"../core/tokenizer":91}],101:[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":95,"./html/index":98,"./javascript/index":104}],102:[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")},{}],103:[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":84,"../core/inputscanner":85,"../core/pattern":88,"../core/templatablepattern":89,"../core/tokenizer":91,"./acorn":102}],107:[function(require,module,exports){!function(t,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define([],r):"object"==typeof exports?exports.Meyda=r():t.Meyda=r()}(this,(function(){return function(t){function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}var e={};return r.m=t,r.c=e,r.i=function(t){return t},r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,r){return Object.prototype.hasOwnProperty.call(t,r)},r.p="",r(r.s=23)}([function(t,r,e){"use strict";function n(t){if(Array.isArray(t)){for(var r=0,e=Array(t.length);r1;)t/=2;return 1===t}function i(t,r){for(var e=[],n=0;n3&&void 0!==arguments[3]?arguments[3]:5,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:2,a=!(arguments.length>5&&void 0!==arguments[5])||arguments[5],u=arguments.length>6&&void 0!==arguments[6]?arguments[6]:440,c=Math.floor(e/2)+1,f=new Array(e).fill(0).map((function(n,o){return t*p(r*o/e,u)}));f[0]=f[1]-1.5*t;var l=f.slice(1).map((function(t,r){return Math.max(t-f[r])}),1).concat([1]),s=Math.round(t/2),y=new Array(t).fill(0).map((function(r,e){return f.map((function(r){return(10*t+s+r-e)%t-s}))})),h=y.map((function(t,r){return t.map((function(t,e){return Math.exp(-.5*Math.pow(2*y[r][e]/l[e],2))}))}));if(h=m(h),i){var b=f.map((function(r){return Math.exp(-.5*Math.pow((r/t-o)/i,2))}));h=h.map((function(t){return t.map((function(t,r){return t*b[r]}))}))}return a&&(h=[].concat(n(h.slice(3)),n(h.slice(0,3)))),h.map((function(t){return t.slice(0,c)}))}function h(t,r,e){if(t.lengtha;)i[u++]=c,a=u*t.barkScale[o.length-1]/24;i[24]=o.length-1;for(var f=0;f<24;f++){for(var l=0,s=i[f];s * @license MIT */ function n(t,r){if(t===r)return 0;for(var e=t.length,n=r.length,o=0,i=Math.min(e,n);o=0;u--)if(c[u]!==f[u])return!1;for(u=c.length-1;u>=0;u--)if(a=c[u],!m(t[a],r[a],e,n))return!1;return!0}function b(t,r,e){m(t,r,!0)&&s(t,r,e,"notDeepStrictEqual",b)}function g(t,r){if(!t||!r)return!1;if("[object RegExp]"==Object.prototype.toString.call(r))return r.test(t);try{if(t instanceof r)return!0}catch(t){}return!Error.isPrototypeOf(r)&&!0===r.call({},t)}function S(t){var r;try{t()}catch(t){r=t}return r}function d(t,r,e,n){var o;if("function"!=typeof r)throw new TypeError('"block" argument must be a function');"string"==typeof e&&(n=e,e=null),o=S(r),n=(e&&e.name?" ("+e.name+").":".")+(n?" "+n:"."),t&&!o&&s(o,e,"Missing expected exception"+n);var i="string"==typeof n,a=!t&&v.isError(o),u=!t&&o&&!e;if((a&&i&&g(o,e)||u)&&s(o,e,"Got unwanted exception"+n),t&&o&&e&&!g(o,e)||!t&&o)throw o}var v=e(33),w=Object.prototype.hasOwnProperty,x=Array.prototype.slice,E=function(){return"foo"===function(){}.name}(),_=t.exports=p,M=/\s*function\s+([^\(\s]*)\s*/;_.AssertionError=function(t){this.name="AssertionError",this.actual=t.actual,this.expected=t.expected,this.operator=t.operator,t.message?(this.message=t.message,this.generatedMessage=!1):(this.message=l(this),this.generatedMessage=!0);var r=t.stackStartFunction||s;if(Error.captureStackTrace)Error.captureStackTrace(this,r);else{var e=new Error;if(e.stack){var n=e.stack,o=u(r),i=n.indexOf("\n"+o);if(i>=0){var a=n.indexOf("\n",i+1);n=n.substring(a+1)}this.stack=n}}},v.inherits(_.AssertionError,Error),_.fail=s,_.ok=p,_.equal=function(t,r,e){t!=r&&s(t,r,e,"==",_.equal)},_.notEqual=function(t,r,e){t==r&&s(t,r,e,"!=",_.notEqual)},_.deepEqual=function(t,r,e){m(t,r,!1)||s(t,r,e,"deepEqual",_.deepEqual)},_.deepStrictEqual=function(t,r,e){m(t,r,!0)||s(t,r,e,"deepStrictEqual",_.deepStrictEqual)},_.notDeepEqual=function(t,r,e){m(t,r,!1)&&s(t,r,e,"notDeepEqual",_.notDeepEqual)},_.notDeepStrictEqual=b,_.strictEqual=function(t,r,e){t!==r&&s(t,r,e,"===",_.strictEqual)},_.notStrictEqual=function(t,r,e){t===r&&s(t,r,e,"!==",_.notStrictEqual)},_.throws=function(t,r,e){d(!0,t,r,e)},_.doesNotThrow=function(t,r,e){d(!1,t,r,e)},_.ifError=function(t){if(t)throw t};var A=Object.keys||function(t){var r=[];for(var e in t)w.call(t,e)&&r.push(e);return r}}).call(r,e(5))},function(t,r,e){"use strict";function n(t){if(Array.isArray(t)){for(var r=0,e=Array(t.length);rr&&(r=t.specific[i]);return Math.pow((t.total-r)/t.total,2)}},function(t,r,e){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};r.a=function(t){if("object"!==n(t.signal))throw new TypeError;for(var r=0,e=0;ei&&a>=0;)e-=t[a],--a;return(a+1)*r}},function(t,r,e){"use strict";var n=e(1),o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};r.a=function(t){if("object"!==o(t.ampSpectrum))throw new TypeError;var r=e.i(n.a)(1,t.ampSpectrum),i=e.i(n.a)(2,t.ampSpectrum),a=e.i(n.a)(3,t.ampSpectrum);return(2*Math.pow(r,3)-3*r*i+a)/Math.pow(Math.sqrt(i-Math.pow(r,2)),3)}},function(t,r,e){"use strict";var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t};r.a=function(t){if("object"!==n(t.ampSpectrum))throw new TypeError;for(var r=0,e=0,o=new Float32Array(t.ampSpectrum.length),i=0,a=0,u=0;u=0&&arguments[0].signal[r+1]<0||arguments[0].signal[r]<0&&arguments[0].signal[r+1]>=0)&&t++;return t}},function(t,r,e){t.exports=e(6).default},function(t,r,e){"use strict";function n(t,r){if(!(t instanceof r))throw new TypeError("Cannot call a class as a function")}e.d(r,"a",(function(){return u}));var o=e(0),i=e(4),a=function(){function t(t,r){for(var e=0;e0;i--)r[t-i]=r[i-1];return r}function o(t){for(var r=Math.PI/(t-1),e=new Float32Array(t),n=0;n1)for(var e=1;e=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),h(e)?n.showHidden=e:e&&r._extend(n,e),w(n.showHidden)&&(n.showHidden=!1),w(n.depth)&&(n.depth=2),w(n.colors)&&(n.colors=!1),w(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=i),c(n,t,n.depth)}function i(t,r){var e=o.styles[r];return e?"["+o.colors[e][0]+"m"+t+"["+o.colors[e][1]+"m":t}function a(t,r){return t}function u(t){var r={};return t.forEach((function(t,e){r[t]=!0})),r}function c(t,e,n){if(t.customInspect&&e&&A(e.inspect)&&e.inspect!==r.inspect&&(!e.constructor||e.constructor.prototype!==e)){var o=e.inspect(n,t);return d(o)||(o=c(t,o,n)),o}var i=f(t,e);if(i)return i;var a=Object.keys(e),h=u(a);if(t.showHidden&&(a=Object.getOwnPropertyNames(e)),M(e)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return l(e);if(0===a.length){if(A(e)){var b=e.name?": "+e.name:"";return t.stylize("[Function"+b+"]","special")}if(x(e))return t.stylize(RegExp.prototype.toString.call(e),"regexp");if(_(e))return t.stylize(Date.prototype.toString.call(e),"date");if(M(e))return l(e)}var g="",S=!1,v=["{","}"];if(y(e)&&(S=!0,v=["[","]"]),A(e)){g=" [Function"+(e.name?": "+e.name:"")+"]"}if(x(e)&&(g=" "+RegExp.prototype.toString.call(e)),_(e)&&(g=" "+Date.prototype.toUTCString.call(e)),M(e)&&(g=" "+l(e)),0===a.length&&(!S||0==e.length))return v[0]+g+v[1];if(n<0)return x(e)?t.stylize(RegExp.prototype.toString.call(e),"regexp"):t.stylize("[Object]","special");t.seen.push(e);var w;return w=S?s(t,e,n,h,a):a.map((function(r){return p(t,e,n,h,r,S)})),t.seen.pop(),m(w,g,v)}function f(t,r){if(w(r))return t.stylize("undefined","undefined");if(d(r)){var e="'"+JSON.stringify(r).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return t.stylize(e,"string")}return S(r)?t.stylize(""+r,"number"):h(r)?t.stylize(""+r,"boolean"):b(r)?t.stylize("null","null"):void 0}function l(t){return"["+Error.prototype.toString.call(t)+"]"}function s(t,r,e,n,o){for(var i=[],a=0,u=r.length;a-1&&(u=i?u.split("\n").map((function(t){return" "+t})).join("\n").substr(2):"\n"+u.split("\n").map((function(t){return" "+t})).join("\n"))):u=t.stylize("[Circular]","special")),w(a)){if(i&&o.match(/^\d+$/))return u;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=t.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=t.stylize(a,"string"))}return a+": "+u}function m(t,r,e){var n=0;return t.reduce((function(t,r){return n++,r.indexOf("\n")>=0&&n++,t+r.replace(/\u001b\[\d\d?m/g,"").length+1}),0)>60?e[0]+(""===r?"":r+"\n ")+" "+t.join(",\n ")+" "+e[1]:e[0]+r+" "+t.join(", ")+" "+e[1]}function y(t){return Array.isArray(t)}function h(t){return"boolean"==typeof t}function b(t){return null===t}function g(t){return null==t}function S(t){return"number"==typeof t}function d(t){return"string"==typeof t}function v(t){return"symbol"==typeof t}function w(t){return void 0===t}function x(t){return E(t)&&"[object RegExp]"===T(t)}function E(t){return"object"==typeof t&&null!==t}function _(t){return E(t)&&"[object Date]"===T(t)}function M(t){return E(t)&&("[object Error]"===T(t)||t instanceof Error)}function A(t){return"function"==typeof t}function j(t){return null===t||"boolean"==typeof t||"number"==typeof t||"string"==typeof t||"symbol"==typeof t||void 0===t}function T(t){return Object.prototype.toString.call(t)}function F(t){return t<10?"0"+t.toString(10):t.toString(10)}function k(){var t=new Date,r=[F(t.getHours()),F(t.getMinutes()),F(t.getSeconds())].join(":");return[t.getDate(),R[t.getMonth()],r].join(" ")}function z(t,r){return Object.prototype.hasOwnProperty.call(t,r)}var O=/%[sdj%]/g;r.format=function(t){if(!d(t)){for(var r=[],e=0;e=i)return t;switch(t){case"%s":return String(n[e++]);case"%d":return Number(n[e++]);case"%j":try{return JSON.stringify(n[e++])}catch(t){return"[Circular]"}default:return t}})),u=n[e];e1){for(var i=1;i65536)throw new Error("requested too many random bytes");var rawBytes=new global.Uint8Array(size);if(size>0){crypto.getRandomValues(rawBytes)}var bytes=Buffer.from(rawBytes.buffer);if(typeof cb==="function"){return process.nextTick((function(){cb(null,bytes)}))}return bytes}}).call(this)}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{_process:112,"safe-buffer":127}],116:[function(require,module,exports){"use strict";var processNextTick=require("process-nextick-args").nextTick;var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){keys.push(key)}return keys};module.exports=Duplex;var util=require("core-util-is");util.inherits=require("inherits");var Readable=require("./_stream_readable");var Writable=require("./_stream_writable");util.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)stream.emit("error",new Error("stream.unshift() after end event"));else addChunk(stream,state,chunk,true)}else if(state.ended){stream.emit("error",new Error("stream.push() after EOF"))}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}}return needMoreData(state)}function addChunk(stream,state,chunk,addToFront){if(state.flowing&&state.length===0&&!state.sync){stream.emit("data",chunk);stream.read(0)}else{state.length+=state.objectMode?1:chunk.length;if(addToFront)state.buffer.unshift(chunk);else state.buffer.push(chunk);if(state.needReadable)emitReadable(stream)}maybeReadMore(stream,state)}function chunkInvalid(state,chunk){var er;if(!_isUint8Array(chunk)&&typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}return er}function needMoreData(state){return!state.ended&&(state.needReadable||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.length>=state.highWaterMark||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=true;n=0}else{state.length-=n}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){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;emitReadable(stream)}function emitReadable(stream){var state=stream._readableState;state.needReadable=false;if(!state.emittedReadable){debug("emitReadable",state.flowing);state.emittedReadable=true;if(state.sync)processNextTick(emitReadable_,stream);else emitReadable_(stream)}}function emitReadable_(stream){debug("emit readable");stream.emit("readable");flow(stream)}function maybeReadMore(stream,state){if(!state.readingMore){state.readingMore=true;processNextTick(maybeReadMore_,stream,state)}}function maybeReadMore_(stream,state){var len=state.length;while(!state.reading&&!state.flowing&&!state.ended&&state.length1&&indexOf(state.pipes,dest)!==-1)&&!cleanedUp){debug("false write response, pause",src._readableState.awaitDrain);src._readableState.awaitDrain++;increasedAwaitDrain=true}src.pause()}}function onerror(er){debug("onerror",er);unpipe();dest.removeListener("error",onerror);if(EElistenerCount(dest,"error")===0)dest.emit("error",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(){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;i=state.length){if(state.decoder)ret=state.buffer.join("");else if(state.buffer.length===1)ret=state.buffer.head.data;else ret=state.buffer.concat(state.length);state.buffer.clear()}else{ret=fromListPartial(n,state.buffer,state.decoder)}return ret}function fromListPartial(n,list,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)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=str.slice(nb)}break}++c}list.length-=c;return ret}function copyFromBuffer(n,list){var ret=Buffer.allocUnsafe(n);var p=list.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)list.head=p.next;else list.head=list.tail=null}else{list.head=p;p.data=buf.slice(nb)}break}++c}list.length-=c;return ret}function endReadable(stream){var state=stream._readableState;if(state.length>0)throw new Error('"endReadable()" called on non-empty stream');if(!state.endEmitted){state.ended=true;processNextTick(endReadableNT,state,stream)}}function endReadableNT(state,stream){if(!state.endEmitted&&state.length===0){state.endEmitted=true;stream.readable=false;stream.emit("end")}}function forEach(xs,f){for(var i=0,l=xs.length;i-1?setImmediate:processNextTick;var Duplex;Writable.WritableState=WritableState;var util=require("core-util-is");util.inherits=require("inherits");var internalUtil={deprecate:require("util-deprecate")};var Stream=require("./internal/streams/stream");var Buffer=require("safe-buffer").Buffer;var OurUint8Array=global.Uint8Array||function(){};function _uint8ArrayToBuffer(chunk){return Buffer.from(chunk)}function _isUint8Array(obj){return Buffer.isBuffer(obj)||obj instanceof OurUint8Array}var destroyImpl=require("./internal/streams/destroy");util.inherits(Writable,Stream);function nop(){}function WritableState(options,stream){Duplex=Duplex||require("./_stream_duplex");options=options||{};var isDuplex=stream instanceof Duplex;this.objectMode=!!options.objectMode;if(isDuplex)this.objectMode=this.objectMode||!!options.writableObjectMode;var hwm=options.highWaterMark;var writableHwm=options.writableHighWaterMark;var defaultHwm=this.objectMode?16:16*1024;if(hwm||hwm===0)this.highWaterMark=hwm;else if(isDuplex&&(writableHwm||writableHwm===0))this.highWaterMark=writableHwm;else this.highWaterMark=defaultHwm;this.highWaterMark=Math.floor(this.highWaterMark);this.finalCalled=false;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;this.destroyed=false;var noDecode=options.decodeStrings===false;this.decodeStrings=!noDecode;this.defaultEncoding=options.defaultEncoding||"utf8";this.length=0;this.writing=false;this.corked=0;this.sync=true;this.bufferProcessing=false;this.onwrite=function(er){onwrite(stream,er)};this.writecb=null;this.writelen=0;this.bufferedRequest=null;this.lastBufferedRequest=null;this.pendingcb=0;this.prefinished=false;this.errorEmitted=false;this.bufferedRequestCount=0;this.corkedRequestsFree=new CorkedRequest(this)}WritableState.prototype.getBuffer=function getBuffer(){var current=this.bufferedRequest;var out=[];while(current){out.push(current);current=current.next}return out};(function(){try{Object.defineProperty(WritableState.prototype,"buffer",{get:internalUtil.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer "+"instead.","DEP0003")})}catch(_){}})();var realHasInstance;if(typeof Symbol==="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==="function"){realHasInstance=Function.prototype[Symbol.hasInstance];Object.defineProperty(Writable,Symbol.hasInstance,{value:function(object){if(realHasInstance.call(this,object))return true;if(this!==Writable)return false;return object&&object._writableState instanceof WritableState}})}else{realHasInstance=function(object){return object instanceof this}}function Writable(options){Duplex=Duplex||require("./_stream_duplex");if(!realHasInstance.call(Writable,this)&&!(this instanceof Duplex)){return new Writable(options)}this._writableState=new WritableState(options,this);this.writable=true;if(options){if(typeof options.write==="function")this._write=options.write;if(typeof options.writev==="function")this._writev=options.writev;if(typeof options.destroy==="function")this._destroy=options.destroy;if(typeof options.final==="function")this._final=options.final}Stream.call(this)}Writable.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function writeAfterEnd(stream,cb){var er=new Error("write after end");stream.emit("error",er);processNextTick(cb,er)}function validChunk(stream,state,chunk,cb){var valid=true;var er=false;if(chunk===null){er=new TypeError("May not write null values to stream")}else if(typeof chunk!=="string"&&chunk!==undefined&&!state.objectMode){er=new TypeError("Invalid non-string/buffer chunk")}if(er){stream.emit("error",er);processNextTick(cb,er);valid=false}return valid}Writable.prototype.write=function(chunk,encoding,cb){var state=this._writableState;var ret=false;var isBuf=!state.objectMode&&_isUint8Array(chunk);if(isBuf&&!Buffer.isBuffer(chunk)){chunk=_uint8ArrayToBuffer(chunk)}if(typeof encoding==="function"){cb=encoding;encoding=null}if(isBuf)encoding="buffer";else if(!encoding)encoding=state.defaultEncoding;if(typeof cb!=="function")cb=nop;if(state.ended)writeAfterEnd(this,cb);else if(isBuf||validChunk(this,state,chunk,cb)){state.pendingcb++;ret=writeOrBuffer(this,state,isBuf,chunk,encoding,cb)}return ret};Writable.prototype.cork=function(){var state=this._writableState;state.corked++};Writable.prototype.uncork=function(){var state=this._writableState;if(state.corked){state.corked--;if(!state.writing&&!state.corked&&!state.finished&&!state.bufferProcessing&&state.bufferedRequest)clearBuffer(this,state)}};Writable.prototype.setDefaultEncoding=function setDefaultEncoding(encoding){if(typeof encoding==="string")encoding=encoding.toLowerCase();if(!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((encoding+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+encoding);this._writableState.defaultEncoding=encoding;return this};function decodeChunk(state,chunk,encoding){if(!state.objectMode&&state.decodeStrings!==false&&typeof chunk==="string"){chunk=Buffer.from(chunk,encoding)}return chunk}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};BufferList.prototype.unshift=function unshift(v){var entry={data:v,next:this.head};if(this.length===0)this.tail=entry;this.head=entry;++this.length};BufferList.prototype.shift=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};BufferList.prototype.clear=function clear(){this.head=this.tail=null;this.length=0};BufferList.prototype.join=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};BufferList.prototype.concat=function concat(n){if(this.length===0)return Buffer.alloc(0);if(this.length===1)return this.head.data;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};return BufferList}();if(util&&util.inspect&&util.inspect.custom){module.exports.prototype[util.inspect.custom]=function(){var obj=util.inspect({length:this.length});return this.constructor.name+" "+obj}}},{"safe-buffer":127,util:25}],122:[function(require,module,exports){"use strict";var processNextTick=require("process-nextick-args").nextTick;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&&(!this._writableState||!this._writableState.errorEmitted)){processNextTick(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){processNextTick(emitErrorNT,_this,err);if(_this._writableState){_this._writableState.errorEmitted=true}}else if(cb){cb(err)}}));return this}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.finished=false;this._writableState.errorEmitted=false}}function emitErrorNT(self,err){self.emit("error",err)}module.exports={destroy:destroy,undestroy:undestroy}},{"process-nextick-args":111}],123:[function(require,module,exports){module.exports=require("events").EventEmitter},{events:26}],124:[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")},{"./lib/_stream_duplex.js":116,"./lib/_stream_passthrough.js":117,"./lib/_stream_readable.js":118,"./lib/_stream_transform.js":119,"./lib/_stream_writable.js":120}],125:[function(require,module,exports){(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):global.createREGL=factory()})(this,(function(){"use strict";var isTypedArray=function(x){return x instanceof Uint8Array||x instanceof Uint16Array||x instanceof Uint32Array||x instanceof Int8Array||x instanceof Int16Array||x instanceof Int32Array||x instanceof Float32Array||x instanceof Float64Array||x instanceof Uint8ClampedArray};var extend=function(base,opts){var keys=Object.keys(opts);for(var i=0;i=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}))},{}],126:[function(require,module,exports){(function(global){(function(){module.exports=global.performance&&global.performance.now?function now(){return performance.now()}:Date.now||function now(){return+new Date}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],127:[function(require,module,exports){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)}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:27}],128:[function(require,module,exports){"use strict";module.exports=require("./lib/index")},{"./lib/index":133}],129:[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]}module.exports={characters:characters,seed:setSeed,lookup:lookup,shuffled:getShuffled}},{"./random/random-from-seed":136}],130:[function(require,module,exports){"use strict";var encode=require("./encode");var alphabet=require("./alphabet");var REDUCE_TIME=1459707606518;var version=6;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+encode(alphabet.lookup,version);str=str+encode(alphabet.lookup,clusterWorkerId);if(counter>0){str=str+encode(alphabet.lookup,counter)}str=str+encode(alphabet.lookup,seconds);return str}module.exports=build},{"./alphabet":129,"./encode":132}],131:[function(require,module,exports){"use strict";var alphabet=require("./alphabet");function decode(id){var characters=alphabet.shuffled();return{version:characters.indexOf(id.substr(0,1))&15,worker:characters.indexOf(id.substr(1,1))&15}}module.exports=decode},{"./alphabet":129}],132:[function(require,module,exports){"use strict";var randomByte=require("./random/random-byte");function encode(lookup,number){var loopCounter=0;var done;var str="";while(!done){str=str+lookup(number>>4*loopCounter&15|randomByte());done=numberMAX_BUFFERED_AMOUNT){self._debug("start backpressure: bufferedAmount %d",self._channel.bufferedAmount);self._cb=cb}else{cb(null)}}else{self._debug("write before connect");self._chunk=chunk;self._cb=cb}};Peer.prototype._onFinish=function(){var self=this;if(self.destroyed)return;if(self.connected){destroySoon()}else{self.once("connect",destroySoon)}function destroySoon(){setTimeout((function(){self.destroy()}),1e3)}};Peer.prototype._createOffer=function(){var self=this;if(self.destroyed)return;self._pc.createOffer((function(offer){if(self.destroyed)return;offer.sdp=self.sdpTransform(offer.sdp);self._pc.setLocalDescription(offer,onSuccess,onError);function onSuccess(){self._debug("createOffer success");if(self.destroyed)return;if(self.trickle||self._iceComplete)sendOffer();else self.once("_iceComplete",sendOffer)}function onError(err){self.destroy(makeError(err,"ERR_SET_LOCAL_DESCRIPTION"))}function sendOffer(){var signal=self._pc.localDescription||offer;self._debug("signal");self.emit("signal",{type:signal.type,sdp:signal.sdp})}}),(function(err){self.destroy(makeError(err,"ERR_CREATE_OFFER"))}),self.offerConstraints)};Peer.prototype._createAnswer=function(){var self=this;if(self.destroyed)return;self._pc.createAnswer((function(answer){if(self.destroyed)return;answer.sdp=self.sdpTransform(answer.sdp);self._pc.setLocalDescription(answer,onSuccess,onError);function onSuccess(){if(self.destroyed)return;if(self.trickle||self._iceComplete)sendAnswer();else self.once("_iceComplete",sendAnswer)}function onError(err){self.destroy(makeError(err,"ERR_SET_LOCAL_DESCRIPTION"))}function sendAnswer(){var signal=self._pc.localDescription||answer;self._debug("signal");self.emit("signal",{type:signal.type,sdp:signal.sdp})}}),(function(err){self.destroy(makeError(err,"ERR_CREATE_ANSWER"))}),self.answerConstraints)};Peer.prototype._onIceStateChange=function(){var self=this;if(self.destroyed)return;var iceConnectionState=self._pc.iceConnectionState;var iceGatheringState=self._pc.iceGatheringState;self._debug("iceStateChange (connection: %s) (gathering: %s)",iceConnectionState,iceGatheringState);self.emit("iceStateChange",iceConnectionState,iceGatheringState);if(iceConnectionState==="connected"||iceConnectionState==="completed"){self._pcReady=true;self._maybeReady()}if(iceConnectionState==="failed"){self.destroy(makeError("Ice connection failed.","ERR_ICE_CONNECTION_FAILURE"))}if(iceConnectionState==="closed"){self.destroy(new Error("Ice connection closed."))}};Peer.prototype.getStats=function(cb){var self=this;if(self._pc.getStats.length===0){self._pc.getStats().then((function(res){var reports=[];res.forEach((function(report){reports.push(report)}));cb(null,reports)}),(function(err){cb(err)}))}else if(self._isReactNativeWebrtc){self._pc.getStats(null,(function(res){var reports=[];res.forEach((function(report){reports.push(report)}));cb(null,reports)}),(function(err){cb(err)}))}else if(self._pc.getStats.length>0){self._pc.getStats((function(res){if(self.destroyed)return;var reports=[];res.result().forEach((function(result){var report={};result.names().forEach((function(name){report[name]=result.stat(name)}));report.id=result.id;report.type=result.type;report.timestamp=result.timestamp;reports.push(report)}));cb(null,reports)}),(function(err){cb(err)}))}else{cb(null,[])}};Peer.prototype._maybeReady=function(){var self=this;self._debug("maybeReady pc %s channel %s",self._pcReady,self._channelReady);if(self.connected||self._connecting||!self._pcReady||!self._channelReady)return;self._connecting=true;function findCandidatePair(){if(self.destroyed)return;self.getStats((function(err,items){if(self.destroyed)return;if(err)items=[];var remoteCandidates={};var localCandidates={};var candidatePairs={};var foundSelectedCandidatePair=false;items.forEach((function(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}}));items.forEach((function(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)}}));function setSelectedCandidatePair(selectedCandidatePair){foundSelectedCandidatePair=true;var local=localCandidates[selectedCandidatePair.localCandidateId];if(local&&local.ip){self.localAddress=local.ip;self.localPort=Number(local.port)}else if(local&&local.ipAddress){self.localAddress=local.ipAddress;self.localPort=Number(local.portNumber)}else if(typeof selectedCandidatePair.googLocalAddress==="string"){local=selectedCandidatePair.googLocalAddress.split(":");self.localAddress=local[0];self.localPort=Number(local[1])}var remote=remoteCandidates[selectedCandidatePair.remoteCandidateId];if(remote&&remote.ip){self.remoteAddress=remote.ip;self.remotePort=Number(remote.port)}else if(remote&&remote.ipAddress){self.remoteAddress=remote.ipAddress;self.remotePort=Number(remote.portNumber)}else if(typeof selectedCandidatePair.googRemoteAddress==="string"){remote=selectedCandidatePair.googRemoteAddress.split(":");self.remoteAddress=remote[0];self.remotePort=Number(remote[1])}self.remoteFamily="IPv4";self._debug("connect local: %s:%s remote: %s:%s",self.localAddress,self.localPort,self.remoteAddress,self.remotePort)}if(!foundSelectedCandidatePair&&(!Object.keys(candidatePairs).length||Object.keys(localCandidates).length)){setTimeout(findCandidatePair,100);return}else{self._connecting=false;self.connected=true}if(self._chunk){try{self.send(self._chunk)}catch(err){return self.destroy(makeError(err,"ERR_DATA_CHANNEL"))}self._chunk=null;self._debug('sent chunk from "write before connect"');var cb=self._cb;self._cb=null;cb(null)}if(typeof self._channel.bufferedAmountLowThreshold!=="number"){self._interval=setInterval((function(){self._onInterval()}),150);if(self._interval.unref)self._interval.unref()}self._debug("connect");self.emit("connect")}))}findCandidatePair()};Peer.prototype._onInterval=function(){var self=this;if(!self._cb||!self._channel||self._channel.bufferedAmount>MAX_BUFFERED_AMOUNT){return}self._onChannelBufferedAmountLow()};Peer.prototype._onSignalingStateChange=function(){var self=this;if(self.destroyed)return;if(self._pc.signalingState==="stable"){self._isNegotiating=false;self._debug("flushing sender queue",self._sendersAwaitingStable);self._sendersAwaitingStable.forEach((function(sender){self.removeTrack(sender);self._queuedNegotiation=true}));self._sendersAwaitingStable=[];if(self._queuedNegotiation){self._debug("flushing negotiation queue");self._queuedNegotiation=false;self._needsNegotiation()}self._debug("negotiate");self.emit("negotiate")}self._debug("signalingStateChange %s",self._pc.signalingState);self.emit("signalingStateChange",self._pc.signalingState)};Peer.prototype._onIceCandidate=function(event){var self=this;if(self.destroyed)return;if(event.candidate&&self.trickle){self.emit("signal",{candidate:{candidate:event.candidate.candidate,sdpMLineIndex:event.candidate.sdpMLineIndex,sdpMid:event.candidate.sdpMid}})}else if(!event.candidate){self._iceComplete=true;self.emit("_iceComplete")}};Peer.prototype._onChannelMessage=function(event){var self=this;if(self.destroyed)return;var data=event.data;if(data instanceof ArrayBuffer)data=Buffer.from(data);self.push(data)};Peer.prototype._onChannelBufferedAmountLow=function(){var self=this;if(self.destroyed||!self._cb)return;self._debug("ending backpressure: bufferedAmount %d",self._channel.bufferedAmount);var cb=self._cb;self._cb=null;cb(null)};Peer.prototype._onChannelOpen=function(){var self=this;if(self.connected||self.destroyed)return;self._debug("on channel open");self._channelReady=true;self._maybeReady()};Peer.prototype._onChannelClose=function(){var self=this;if(self.destroyed)return;self._debug("on channel close");self.destroy()};Peer.prototype._onTrack=function(event){var self=this;if(self.destroyed)return;event.streams.forEach((function(eventStream){self._debug("on track");self.emit("track",event.track,eventStream);self._remoteTracks.push({track:event.track,stream:eventStream});if(self._remoteStreams.some((function(remoteStream){return remoteStream.id===eventStream.id})))return;self._remoteStreams.push(eventStream);setTimeout((function(){self.emit("stream",eventStream)}),0)}))};Peer.prototype._debug=function(){var self=this;var args=[].slice.call(arguments);args[0]="["+self._id+"] "+args[0];debug.apply(null,args)};Peer.prototype._transformConstraints=function(constraints){var self=this;if(Object.keys(constraints).length===0){return constraints}if((constraints.mandatory||constraints.optional)&&!self._isChromium){var newConstraints=Object.assign({},constraints.optional,constraints.mandatory);if(newConstraints.OfferToReceiveVideo!==undefined){newConstraints.offerToReceiveVideo=newConstraints.OfferToReceiveVideo;delete newConstraints["OfferToReceiveVideo"]}if(newConstraints.OfferToReceiveAudio!==undefined){newConstraints.offerToReceiveAudio=newConstraints.OfferToReceiveAudio;delete newConstraints["OfferToReceiveAudio"]}return newConstraints}else if(!constraints.mandatory&&!constraints.optional&&self._isChromium){if(constraints.offerToReceiveVideo!==undefined){constraints.OfferToReceiveVideo=constraints.offerToReceiveVideo;delete constraints["offerToReceiveVideo"]}if(constraints.offerToReceiveAudio!==undefined){constraints.OfferToReceiveAudio=constraints.offerToReceiveAudio;delete constraints["offerToReceiveAudio"]}return{mandatory:constraints}}return constraints};function makeError(message,code){var err=new Error(message);err.code=code;return err}function noop(){}}).call(this)}).call(this,require("buffer").Buffer)},{buffer:27,debug:139,"get-browser-rtc":55,inherits:80,randombytes:115,"readable-stream":124}],139:[function(require,module,exports){(function(process){(function(){exports=module.exports=require("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage="undefined"!=typeof chrome&&"undefined"!=typeof chrome.storage?chrome.storage.local:localstorage();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"){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+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return;var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0;var lastC=0;args[0].replace(/%[a-zA-Z%]/g,(function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}}));args.splice(lastC,0,c)}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}}).call(this)}).call(this,require("_process"))},{"./debug":140,_process:112}],140:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{dup:50,ms:141}],141:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51}],142:[function(require,module,exports){var url=require("./url");var parser=require("socket.io-parser");var Manager=require("./manager");var debug=require("debug")("socket.io-client");module.exports=exports=lookup;var cache=exports.managers={};function lookup(uri,opts){if(typeof uri==="object"){opts=uri;uri=undefined}opts=opts||{};var parsed=url(uri);var source=parsed.source;var id=parsed.id;var path=parsed.path;var sameNamespace=cache[id]&&path in cache[id].nsps;var newConnection=opts.forceNew||opts["force new connection"]||false===opts.multiplex||sameNamespace;var io;if(newConnection){debug("ignoring socket cache for %s",source);io=Manager(source,opts)}else{if(!cache[id]){debug("new io instance for %s",source);cache[id]=Manager(source,opts)}io=cache[id]}if(parsed.query&&!opts.query){opts.query=parsed.query}return io.socket(parsed.path,opts)}exports.protocol=parser.protocol;exports.connect=lookup;exports.Manager=require("./manager");exports.Socket=require("./socket")},{"./manager":143,"./socket":145,"./url":146,debug:148,"socket.io-parser":153}],143:[function(require,module,exports){var eio=require("engine.io-client");var Socket=require("./socket");var Emitter=require("component-emitter");var parser=require("socket.io-parser");var on=require("./on");var bind=require("component-bind");var debug=require("debug")("socket.io-client:manager");var indexOf=require("indexof");var Backoff=require("backo2");var has=Object.prototype.hasOwnProperty;module.exports=Manager;function Manager(uri,opts){if(!(this instanceof Manager))return new Manager(uri,opts);if(uri&&"object"===typeof uri){opts=uri;uri=undefined}opts=opts||{};opts.path=opts.path||"/socket.io";this.nsps={};this.subs=[];this.opts=opts;this.reconnection(opts.reconnection!==false);this.reconnectionAttempts(opts.reconnectionAttempts||Infinity);this.reconnectionDelay(opts.reconnectionDelay||1e3);this.reconnectionDelayMax(opts.reconnectionDelayMax||5e3);this.randomizationFactor(opts.randomizationFactor||.5);this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()});this.timeout(null==opts.timeout?2e4:opts.timeout);this.readyState="closed";this.uri=uri;this.connecting=[];this.lastPing=null;this.encoding=false;this.packetBuffer=[];var _parser=opts.parser||parser;this.encoder=new _parser.Encoder;this.decoder=new _parser.Decoder;this.autoConnect=opts.autoConnect!==false;if(this.autoConnect)this.open()}Manager.prototype.emitAll=function(){this.emit.apply(this,arguments);for(var nsp in this.nsps){if(has.call(this.nsps,nsp)){this.nsps[nsp].emit.apply(this.nsps[nsp],arguments)}}};Manager.prototype.updateSocketIds=function(){for(var nsp in this.nsps){if(has.call(this.nsps,nsp)){this.nsps[nsp].id=this.generateId(nsp)}}};Manager.prototype.generateId=function(nsp){return(nsp==="/"?"":nsp+"#")+this.engine.id};Emitter(Manager.prototype);Manager.prototype.reconnection=function(v){if(!arguments.length)return this._reconnection;this._reconnection=!!v;return this};Manager.prototype.reconnectionAttempts=function(v){if(!arguments.length)return this._reconnectionAttempts;this._reconnectionAttempts=v;return this};Manager.prototype.reconnectionDelay=function(v){if(!arguments.length)return this._reconnectionDelay;this._reconnectionDelay=v;this.backoff&&this.backoff.setMin(v);return this};Manager.prototype.randomizationFactor=function(v){if(!arguments.length)return this._randomizationFactor;this._randomizationFactor=v;this.backoff&&this.backoff.setJitter(v);return this};Manager.prototype.reconnectionDelayMax=function(v){if(!arguments.length)return this._reconnectionDelayMax;this._reconnectionDelayMax=v;this.backoff&&this.backoff.setMax(v);return this};Manager.prototype.timeout=function(v){if(!arguments.length)return this._timeout;this._timeout=v;return this};Manager.prototype.maybeReconnectOnOpen=function(){if(!this.reconnecting&&this._reconnection&&this.backoff.attempts===0){this.reconnect()}};Manager.prototype.open=Manager.prototype.connect=function(fn,opts){debug("readyState %s",this.readyState);if(~this.readyState.indexOf("open"))return this;debug("opening %s",this.uri);this.engine=eio(this.uri,this.opts);var socket=this.engine;var self=this;this.readyState="opening";this.skipReconnect=false;var openSub=on(socket,"open",(function(){self.onopen();fn&&fn()}));var errorSub=on(socket,"error",(function(data){debug("connect_error");self.cleanup();self.readyState="closed";self.emitAll("connect_error",data);if(fn){var err=new Error("Connection error");err.data=data;fn(err)}else{self.maybeReconnectOnOpen()}}));if(false!==this._timeout){var timeout=this._timeout;debug("connect attempt will timeout after %d",timeout);if(timeout===0){openSub.destroy()}var timer=setTimeout((function(){debug("connect attempt timed out after %d",timeout);openSub.destroy();socket.close();socket.emit("error","timeout");self.emitAll("connect_timeout",timeout)}),timeout);this.subs.push({destroy:function(){clearTimeout(timer)}})}this.subs.push(openSub);this.subs.push(errorSub);return this};Manager.prototype.onopen=function(){debug("open");this.cleanup();this.readyState="open";this.emit("open");var socket=this.engine;this.subs.push(on(socket,"data",bind(this,"ondata")));this.subs.push(on(socket,"ping",bind(this,"onping")));this.subs.push(on(socket,"pong",bind(this,"onpong")));this.subs.push(on(socket,"error",bind(this,"onerror")));this.subs.push(on(socket,"close",bind(this,"onclose")));this.subs.push(on(this.decoder,"decoded",bind(this,"ondecoded")))};Manager.prototype.onping=function(){this.lastPing=new Date;this.emitAll("ping")};Manager.prototype.onpong=function(){this.emitAll("pong",new Date-this.lastPing)};Manager.prototype.ondata=function(data){this.decoder.add(data)};Manager.prototype.ondecoded=function(packet){this.emit("packet",packet)};Manager.prototype.onerror=function(err){debug("error",err);this.emitAll("error",err)};Manager.prototype.socket=function(nsp,opts){var socket=this.nsps[nsp];if(!socket){socket=new Socket(this,nsp,opts);this.nsps[nsp]=socket;var self=this;socket.on("connecting",onConnecting);socket.on("connect",(function(){socket.id=self.generateId(nsp)}));if(this.autoConnect){onConnecting()}}function onConnecting(){if(!~indexOf(self.connecting,socket)){self.connecting.push(socket)}}return socket};Manager.prototype.destroy=function(socket){var index=indexOf(this.connecting,socket);if(~index)this.connecting.splice(index,1);if(this.connecting.length)return;this.close()};Manager.prototype.packet=function(packet){debug("writing packet %j",packet);var self=this;if(packet.query&&packet.type===0)packet.nsp+="?"+packet.query;if(!self.encoding){self.encoding=true;this.encoder.encode(packet,(function(encodedPackets){for(var i=0;i0&&!this.encoding){var pack=this.packetBuffer.shift();this.packet(pack)}};Manager.prototype.cleanup=function(){debug("cleanup");var subsLength=this.subs.length;for(var i=0;i=this._reconnectionAttempts){debug("reconnect failed");this.backoff.reset();this.emitAll("reconnect_failed");this.reconnecting=false}else{var delay=this.backoff.duration();debug("will wait %dms before reconnect attempt",delay);this.reconnecting=true;var timer=setTimeout((function(){if(self.skipReconnect)return;debug("attempting reconnect");self.emitAll("reconnect_attempt",self.backoff.attempts);self.emitAll("reconnecting",self.backoff.attempts);if(self.skipReconnect)return;self.open((function(err){if(err){debug("reconnect attempt error");self.reconnecting=false;self.reconnect();self.emitAll("reconnect_error",err.data)}else{debug("reconnect success");self.onreconnect()}}))}),delay);this.subs.push({destroy:function(){clearTimeout(timer)}})}};Manager.prototype.onreconnect=function(){var attempt=this.backoff.attempts;this.reconnecting=false;this.backoff.reset();this.updateSocketIds();this.emitAll("reconnect",attempt)}},{"./on":144,"./socket":145,backo2:21,"component-bind":34,"component-emitter":147,debug:148,"engine.io-client":39,indexof:79,"socket.io-parser":153}],144:[function(require,module,exports){module.exports=on;function on(obj,ev,fn){obj.on(ev,fn);return{destroy:function(){obj.removeListener(ev,fn)}}}},{}],145:[function(require,module,exports){var parser=require("socket.io-parser");var Emitter=require("component-emitter");var toArray=require("to-array");var on=require("./on");var bind=require("component-bind");var debug=require("debug")("socket.io-client:socket");var parseqs=require("parseqs");var hasBin=require("has-binary2");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,connecting:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1,ping:1,pong:1};var emit=Emitter.prototype.emit;function Socket(io,nsp,opts){this.io=io;this.nsp=nsp;this.json=this;this.ids=0;this.acks={};this.receiveBuffer=[];this.sendBuffer=[];this.connected=false;this.disconnected=true;this.flags={};if(opts&&opts.query){this.query=opts.query}if(this.io.autoConnect)this.open()}Emitter(Socket.prototype);Socket.prototype.subEvents=function(){if(this.subs)return;var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]};Socket.prototype.open=Socket.prototype.connect=function(){if(this.connected)return this;this.subEvents();if(!this.io.reconnecting)this.io.open();if("open"===this.io.readyState)this.onopen();this.emit("connecting");return this};Socket.prototype.send=function(){var args=toArray(arguments);args.unshift("message");this.emit.apply(this,args);return this};Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev)){emit.apply(this,arguments);return this}var args=toArray(arguments);var packet={type:(this.flags.binary!==undefined?this.flags.binary:hasBin(args))?parser.BINARY_EVENT:parser.EVENT,data:args};packet.options={};packet.options.compress=!this.flags||false!==this.flags.compress;if("function"===typeof args[args.length-1]){debug("emitting packet with ack id %d",this.ids);this.acks[this.ids]=args.pop();packet.id=this.ids++}if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}this.flags={};return this};Socket.prototype.packet=function(packet){packet.nsp=this.nsp;this.io.packet(packet)};Socket.prototype.onopen=function(){debug("transport is open - connecting");if("/"!==this.nsp){if(this.query){var query=typeof this.query==="object"?parseqs.encode(this.query):this.query;debug("sending connect packet with query %s",query);this.packet({type:parser.CONNECT,query:query})}else{this.packet({type:parser.CONNECT})}}};Socket.prototype.onclose=function(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;delete this.id;this.emit("disconnect",reason)};Socket.prototype.onpacket=function(packet){var sameNamespace=packet.nsp===this.nsp;var rootNamespaceError=packet.type===parser.ERROR&&packet.nsp==="/";if(!sameNamespace&&!rootNamespaceError)return;switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data);break}};Socket.prototype.onevent=function(packet){var 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){emit.apply(this,args)}else{this.receiveBuffer.push(args)}};Socket.prototype.ack=function(id){var self=this;var sent=false;return function(){if(sent)return;sent=true;var args=toArray(arguments);debug("sending ack %j",args);self.packet({type:hasBin(args)?parser.BINARY_ACK:parser.ACK,id:id,data:args})}};Socket.prototype.onack=function(packet){var 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)}};Socket.prototype.onconnect=function(){this.connected=true;this.disconnected=false;this.emit("connect");this.emitBuffered()};Socket.prototype.emitBuffered=function(){var i;for(i=0;i=31||typeof navigator!=="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return;var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0;var lastC=0;args[0].replace(/%[a-zA-Z%]/g,(function(match){if("%%"===match)return;index++;if("%c"===match){lastC=index}}));args.splice(lastC,0,c)}function log(){return"object"===typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){exports.storage.removeItem("debug")}else{exports.storage.debug=namespaces}}catch(e){}}function load(){var r;try{r=exports.storage.debug}catch(e){}if(!r&&typeof process!=="undefined"&&"env"in process){r=process.env.DEBUG}return r}exports.enable(load());function localstorage(){try{return window.localStorage}catch(e){}}}).call(this)}).call(this,require("_process"))},{"./debug":149,_process:112}],149:[function(require,module,exports){arguments[4][50][0].apply(exports,arguments)},{dup:50,ms:151}],150:[function(require,module,exports){arguments[4][57][0].apply(exports,arguments)},{dup:57}],151:[function(require,module,exports){arguments[4][51][0].apply(exports,arguments)},{dup:51}],152:[function(require,module,exports){var isArray=require("isarray");var isBuf=require("./is-buffer");var toString=Object.prototype.toString;var withNativeBlob=typeof Blob==="function"||typeof Blob!=="undefined"&&toString.call(Blob)==="[object BlobConstructor]";var withNativeFile=typeof File==="function"||typeof File!=="undefined"&&toString.call(File)==="[object FileConstructor]";exports.deconstructPacket=function(packet){var buffers=[];var packetData=packet.data;var pack=packet;pack.data=_deconstructPacket(packetData,buffers);pack.attachments=buffers.length;return{packet:pack,buffers:buffers}};function _deconstructPacket(data,buffers){if(!data)return data;if(isBuf(data)){var placeholder={_placeholder:true,num:buffers.length};buffers.push(data);return placeholder}else if(isArray(data)){var newData=new Array(data.length);for(var i=0;i>5===6)return 2;else if(byte>>4===14)return 3;else if(byte>>3===30)return 4;return-1}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"�".repeat(p)}if(self.lastNeed>1&&buf.length>1){if((buf[1]&192)!==128){self.lastNeed=1;return"�".repeat(p+1)}if(self.lastNeed>2&&buf.length>2){if((buf[2]&192)!==128){self.lastNeed=2;return"�".repeat(p+2)}}}}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+"�".repeat(this.lastTotal-this.lastNeed);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":127}],156:[function(require,module,exports){function Agent(){this._defaults=[]}["use","on","once","set","query","type","accept","auth","withCredentials","sortQuery","retry","ok","redirects","timeout","buffer","serialize","parse","ca","key","pfx","cert"].forEach((function(fn){Agent.prototype[fn]=function(){this._defaults.push({fn:fn,arguments:arguments});return this}}));Agent.prototype._setDefaults=function(req){this._defaults.forEach((function(def){req[def.fn].apply(req,def.arguments)}))};module.exports=Agent},{}],157:[function(require,module,exports){var root;if(typeof window!=="undefined"){root=window}else if(typeof self!=="undefined"){root=self}else{console.warn("Using browser-only version of superagent in non-browser environment");root=this}var Emitter=require("component-emitter");var RequestBase=require("./request-base");var isObject=require("./is-object");var ResponseBase=require("./response-base");var Agent=require("./agent-base");function noop(){}var request=exports=module.exports=function(method,url){if("function"==typeof url){return new exports.Request("GET",method).end(url)}if(1==arguments.length){return new exports.Request("GET",method)}return new exports.Request(method,url)};exports.Request=Request;request.getXHR=function(){if(root.XMLHttpRequest&&(!root.location||"file:"!=root.location.protocol||!root.ActiveXObject)){return new XMLHttpRequest}else{try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){}}throw Error("Browser-only version of superagent could not find XHR")};var trim="".trim?function(s){return s.trim()}:function(s){return s.replace(/(^\s*|\s*$)/g,"")};function serialize(obj){if(!isObject(obj))return obj;var pairs=[];for(var key in obj){pushEncodedKeyValuePair(pairs,key,obj[key])}return pairs.join("&")}function pushEncodedKeyValuePair(pairs,key,val){if(val!=null){if(Array.isArray(val)){val.forEach((function(v){pushEncodedKeyValuePair(pairs,key,v)}))}else if(isObject(val)){for(var subkey in val){pushEncodedKeyValuePair(pairs,key+"["+subkey+"]",val[subkey])}}else{pairs.push(encodeURIComponent(key)+"="+encodeURIComponent(val))}}else if(val===null){pairs.push(encodeURIComponent(key))}}request.serializeObject=serialize;function parseString(str){var obj={};var pairs=str.split("&");var pair;var pos;for(var i=0,len=pairs.length;i=2&&self._responseTimeoutTimer){clearTimeout(self._responseTimeoutTimer)}if(4!=readyState){return}var status;try{status=xhr.status}catch(e){status=0}if(!status){if(self.timedout||self._aborted)return;return self.crossDomainError()}self.emit("end")};var handleProgress=function(direction,e){if(e.total>0){e.percent=e.loaded/e.total*100}e.direction=direction;self.emit("progress",e)};if(this.hasListeners("progress")){try{xhr.onprogress=handleProgress.bind(null,"download");if(xhr.upload){xhr.upload.onprogress=handleProgress.bind(null,"upload")}}catch(e){}}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&&"GET"!=this.method&&"HEAD"!=this.method&&"string"!=typeof data&&!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(null==this.header[field])continue;if(this.header.hasOwnProperty(field))xhr.setRequestHeader(field,this.header[field])}if(this._responseType){xhr.responseType=this._responseType}this.emit("request",this);xhr.send(typeof data!=="undefined"?data:null);return this};request.agent=function(){return new Agent};["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach((function(method){Agent.prototype[method.toLowerCase()]=function(url,fn){var req=new request.Request(method,url);this._setDefaults(req);if(fn){req.end(fn)}return req}}));Agent.prototype.del=Agent.prototype["delete"];request.get=function(url,data,fn){var req=request("GET",url);if("function"==typeof data)fn=data,data=null;if(data)req.query(data);if(fn)req.end(fn);return req};request.head=function(url,data,fn){var req=request("HEAD",url);if("function"==typeof data)fn=data,data=null;if(data)req.query(data);if(fn)req.end(fn);return req};request.options=function(url,data,fn){var req=request("OPTIONS",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};function del(url,data,fn){var req=request("DELETE",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req}request["del"]=del;request["delete"]=del;request.patch=function(url,data,fn){var req=request("PATCH",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};request.post=function(url,data,fn){var req=request("POST",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req};request.put=function(url,data,fn){var req=request("PUT",url);if("function"==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req}},{"./agent-base":156,"./is-object":158,"./request-base":159,"./response-base":160,"component-emitter":35}],158:[function(require,module,exports){"use strict";function isObject(obj){return null!==obj&&"object"===typeof obj}module.exports=isObject},{}],159:[function(require,module,exports){"use strict";var isObject=require("./is-object");module.exports=RequestBase;function RequestBase(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in RequestBase.prototype){obj[key]=RequestBase.prototype[key]}return obj}RequestBase.prototype.clearTimeout=function _clearTimeout(){clearTimeout(this._timer);clearTimeout(this._responseTimeoutTimer);delete this._timer;delete this._responseTimeoutTimer;return this};RequestBase.prototype.parse=function parse(fn){this._parser=fn;return this};RequestBase.prototype.responseType=function(val){this._responseType=val;return this};RequestBase.prototype.serialize=function serialize(fn){this._serializer=fn;return this};RequestBase.prototype.timeout=function timeout(options){if(!options||"object"!==typeof options){this._timeout=options;this._responseTimeout=0;return this}for(var option in options){switch(option){case"deadline":this._timeout=options.deadline;break;case"response":this._responseTimeout=options.response;break;default:console.warn("Unknown timeout option",option)}}return this};RequestBase.prototype.retry=function retry(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=["ECONNRESET","ETIMEDOUT","EADDRINFO","ESOCKETTIMEDOUT"];RequestBase.prototype._shouldRetry=function(err,res){if(!this._maxRetries||this._retries++>=this._maxRetries){return false}if(this._retryCallback){try{var override=this._retryCallback(err,res);if(override===true)return true;if(override===false)return false}catch(e){console.error(e)}}if(res&&res.status&&res.status>=500&&res.status!=501)return true;if(err){if(err.code&&~ERROR_CODES.indexOf(err.code))return true;if(err.timeout&&err.code=="ECONNABORTED")return true;if(err.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;return this._end()};RequestBase.prototype.then=function then(resolve,reject){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(innerResolve,innerReject){self.end((function(err,res){if(err)innerReject(err);else innerResolve(res)}))}))}return this._fullfilledPromise.then(resolve,reject)};RequestBase.prototype["catch"]=function(cb){return this.then(undefined,cb)};RequestBase.prototype.use=function use(fn){fn(this);return this};RequestBase.prototype.ok=function(cb){if("function"!==typeof cb)throw 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,val){if(isObject(field)){for(var key in field){this.set(key,field[key])}return this}this._header[field.toLowerCase()]=val;this.header[field]=val;return this};RequestBase.prototype.unset=function(field){delete this._header[field.toLowerCase()];delete this.header[field];return this};RequestBase.prototype.field=function(name,val){if(null===name||undefined===name){throw new Error(".field(name, val) name can not be empty")}if(this._data){console.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){this.field(key,name[key])}return this}if(Array.isArray(val)){for(var i in val){this.field(name,val[i])}return this}if(null===val||undefined===val){throw new Error(".field(name, val) val can not be empty")}if("boolean"===typeof val){val=""+val}this._getFormData().append(name,val);return this};RequestBase.prototype.abort=function(){if(this._aborted){return this}this._aborted=true;this.xhr&&this.xhr.abort();this.req&&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 "+base64Encoder(user+":"+pass));break;case"auto":this.username=user;this.password=pass;break;case"bearer":this.set("Authorization","Bearer "+user);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("number"!==typeof n){throw 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 isObj=isObject(data);var type=this._header["content-type"];if(this._formData){console.error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()")}if(isObj&&!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 Error("Can't merge these send calls")}if(isObj&&isObject(this._data)){for(var key in data){this._data[key]=data[key]}}else if("string"==typeof data){if(!type)this.type("form");type=this._header["content-type"];if("application/x-www-form-urlencoded"==type){this._data=this._data?this._data+"&"+data:data}else{this._data=(this._data||"")+data}}else{this._data=data}if(!isObj||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.indexOf("?")>=0?"&":"?")+query}this._query.length=0;if(this._sort){var index=this.url.indexOf("?");if(index>=0){var queryArr=this.url.substring(index+1).split("&");if("function"===typeof this._sort){queryArr.sort(this._sort)}else{queryArr.sort()}this.url=this.url.substring(0,index)+"?"+queryArr.join("&")}}};RequestBase.prototype._appendQueryString=function(){console.trace("Unsupported")};RequestBase.prototype._timeoutError=function(reason,timeout,errno){if(this._aborted){return}var err=new Error(reason+timeout+"ms exceeded");err.timeout=timeout;err.code="ECONNABORTED";err.errno=errno;this.timedout=true;this.abort();this.callback(err)};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)}}},{"./is-object":158}],160:[function(require,module,exports){"use strict";var utils=require("./utils");module.exports=ResponseBase;function ResponseBase(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in ResponseBase.prototype){obj[key]=ResponseBase.prototype[key]}return obj}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 params=utils.params(ct);for(var key in params)this[key]=params[key];this.links={};try{if(header.link){this.links=utils.parseLinks(header.link)}}catch(err){}};ResponseBase.prototype._setStatusProperties=function(status){var type=status/100|0;this.status=this.statusCode=status;this.statusType=type;this.info=1==type;this.ok=2==type;this.redirect=3==type;this.clientError=4==type;this.serverError=5==type;this.error=4==type||5==type?this.toError():false;this.created=201==status;this.accepted=202==status;this.noContent=204==status;this.badRequest=400==status;this.unauthorized=401==status;this.notAcceptable=406==status;this.forbidden=403==status;this.notFound=404==status;this.unprocessableEntity=422==status}},{"./utils":161}],161:[function(require,module,exports){"use strict";exports.type=function(str){return str.split(/ *; */).shift()};exports.params=function(str){return str.split(/ *; */).reduce((function(obj,str){var parts=str.split(/ *= */);var key=parts.shift();var val=parts.shift();if(key&&val)obj[key]=val;return obj}),{})};exports.parseLinks=function(str){return str.split(/ *, */).reduce((function(obj,str){var parts=str.split(/ *; */);var url=parts[0].slice(1,-1);var rel=parts[1].split(/ *= */)[1].slice(1,-1);obj[rel]=url;return obj}),{})};exports.cleanHeader=function(header,changesOrigin){delete header["content-type"];delete header["content-length"];delete header["transfer-encoding"];delete header["host"];if(changesOrigin){delete header["authorization"];delete header["cookie"]}return header}},{}],162:[function(require,module,exports){(function(setImmediate,clearImmediate){(function(){var nextTick=require("process/browser.js").nextTick;var apply=Function.prototype.apply;var slice=Array.prototype.slice;var immediateIds={};var nextImmediateId=0;exports.setTimeout=function(){return new Timeout(apply.call(setTimeout,window,arguments),clearTimeout)};exports.setInterval=function(){return new Timeout(apply.call(setInterval,window,arguments),clearInterval)};exports.clearTimeout=exports.clearInterval=function(timeout){timeout.close()};function Timeout(id,clearFn){this._id=id;this._clearFn=clearFn}Timeout.prototype.unref=Timeout.prototype.ref=function(){};Timeout.prototype.close=function(){this._clearFn.call(window,this._id)};exports.enroll=function(item,msecs){clearTimeout(item._idleTimeoutId);item._idleTimeout=msecs};exports.unenroll=function(item){clearTimeout(item._idleTimeoutId);item._idleTimeout=-1};exports._unrefActive=exports.active=function(item){clearTimeout(item._idleTimeoutId);var msecs=item._idleTimeout;if(msecs>=0){item._idleTimeoutId=setTimeout((function onTimeout(){if(item._onTimeout)item._onTimeout()}),msecs)}};exports.setImmediate=typeof setImmediate==="function"?setImmediate:function(fn){var id=nextImmediateId++;var args=arguments.length<2?false:slice.call(arguments,1);immediateIds[id]=true;nextTick((function onNextTick(){if(immediateIds[id]){if(args){fn.apply(null,args)}else{fn.call(null)}exports.clearImmediate(id)}}));return id};exports.clearImmediate=typeof clearImmediate==="function"?clearImmediate:function(id){delete immediateIds[id]}}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)},{"process/browser.js":112,timers:162}],163:[function(require,module,exports){module.exports=toArray;function toArray(list,index){var array=[];index=index||0;for(var i=index||0;i0);return encoded}function decode(str){var decoded=0;for(i=0;i